Reputation: 971
I'm trying to write a function with a callback function. This is my function with callback
public function functionWithCallback($field, $value, Closure $callback = null)
{
$adminIds = Admin::when(!$callback, function ($query) use ($field, $value) {
$query->where($field, $value);
})->when($callback, $callback($query)) /* Error on this line */
->get()->pluck('id')->toArray();
}
And this is function which call to function has callback in parameter
public function functionCallToCallback()
{
$this->functionWithCallback('id', 1);
}
public function functionCallToCallback2()
{
$this->functionWithCallback('name', 'Test', function ($query) use ($value) {
$query->where('name', 'like', '%' . $value . '%');
});
}
When I run this code, it thrown an exception
Error: Function name must be a string
The error thrown in line which contain this code when($callback, $callback($query))
. But when I comment function functionCallToCallback
, it thrown an another error:
ErrorException: Undefined variable: query
Anyone know how to solve this? Thanks
Upvotes: 1
Views: 630
Reputation: 50491
You are calling the callback instead of passing the callback to when
:
when($callback, $callback($query))
The second argument to when
is a callback:
when($callback, $callback)
Though you shouldn't need this extra call to when
since you can pass both the callbacks to the call to when
:
$adminIds = Admin::when($callback, $callback, function ($query) use ($field, $value) { ... })
->pluck('id')->toArray();
"You may pass another closure as the third argument to the
when
method. This closure will only execute if the first argument evaluates asfalse
."
Side Note: not sure where $value
comes from in functionCallToCallback2
Upvotes: 2