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);
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);
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);