Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Pass classfunction as callback in eager load?

Tags:

php

laravel

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?

like image 328
Adam Avatar asked Oct 18 '25 16:10

Adam


1 Answers

Starting from PHP 7.1.0, you can use Closure::fromCallable (docs):

$users = App\User::with(
  [ 'posts' => \Closure::fromCallable([$this, 'addRestrain']) ]
)->get();

Otherwise, you're limited to using anonymous function wrapping $this->addRestrain call instead.

like image 112
raina77ow Avatar answered Oct 20 '25 04:10

raina77ow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!