Question

Currently I use this following helper:

function whereHasNested($query, $key, $relationship)
{
    if(Input::has($key))
    {
        $callback = function($q) use (&$relationship, &$key, &$callback) {
            if(!$relationship) $q->whereId(Input::get($key));
            else $q->whereHas(array_shift($relationship),$callback);
        };

        $callback($query);
    }
}

This will avoid to have to write multiple whereHas within whereHas. Here is a usage example:

$query = Model::query();

whereHasNested($query, 'package_id', ['club', 'membership', 'package']);

return $query->orderBy('update_at', 'DESC')->paginate(10);

However, how could I convert this to a method in my BaseModel?

So I could chain it like:

$query->whereHasNested($key, $relationship);
Was it helpful?

Solution

That's what Query Scopes are for:

public function scopeWhereHasNested($query, $key, $relationships)
{
    // your code here...
}

// then use it wherever you want

Model::whereHasNested($key, $relationships);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top