Monday, April 3, 2017

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 Users::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();
}



via Josh Petitt

Advertisement