Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Query Builder expression to return empty result

I would like to make a function that can return a Query\Builder that will always return an empty set.

I am making some helper functions and Query\Builder objects get passed around. In certain situations, I always want the result Query\Builder object to return an empty set, regardless of what gets added later.

An example is below. I have a function that returns a query get_users_for_wednesdays, and the result gets passed to another function that adds on a where clause. I don't what to have to check for the existance of a query in filter_for_steves, I just want to modify it and return a query.

Is there an efficient query that always produces an empty set? Ideally one that short-circuits before actually querying the database.

public function get_users_for_wednesdays()
{
   if (is_wednesday())
   {
       return \App\User::query();
   }
   else
   {
       // HOW TO RETURN QUERY FOR EMPTY RESULT SET HERE?
   }
}

public function filter_for_steves($users)
{
    return $users->where('name', 'steve');
}

public getThirdWednesdayStevesAttribute()
{
    $users = get_users_for_wednesday();

    return filter_for_steves($users)->get();
}
like image 227
Josh Petitt Avatar asked Sep 19 '25 18:09

Josh Petitt


1 Answers

Your first two functions should be Scopes.

It makes more sense to put the is_wednesday() check in the function that's building the query, but if you prefer the other way scopeUsersForWednesday() can just return the $query without modifying it when is_wednesday() returns false.

public function scopeUsersForWednesday($query)
{
    // Replace with whatever your actual query should be
    return $query;
}

public function scopeFilterForSteves($query)
{
    return $query->where('name', 'steve');
}

public function getThirdWednesdayStevesAttribute()
{
    $query = User::filterForSteves();

    if (is_wednesday()) {
        $query = $query->usersForWednesday();
    }

    return $query->get();
}
like image 98
Ethan H. Avatar answered Sep 21 '25 08:09

Ethan H.