I use constraint eager load with an anonymous function:
$users = App\User::with(['posts' => function ($query) {
$query->where('title', 'like', '%first%');
}])->get();
Now I want to replace the anonymous function with a class function. According to PHP: How to use a class function as a callback I found
A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.
Thus I expected that the following will work:
public function start()
{
$users = App\User::with(['posts' => [$this, 'addRestrain']])->get();
// ...
}
private function addRestrain($query)
{
$query->where('title', 'like', '%first%');
}
However, Laravel detects that the passed parameter is not a closure, but an array:
"Type error: Argument 3 passed to Illuminate\Database\Eloquent\Builder::eagerLoadRelation() must be an instance of Closure, array given, called in
Does that mean that it is not possible to use a class function for the eager load constraint?