I have a weird value for the parameter inside the closure when I pass this variable to when() method of Laravel Eloquent. Inside the closure, for $user_id
I get true
instead of 2
. What might be the reason for that?
$user_id = 2;
$orders = Order::with('user')
->when(!empty($user_id), function ($query, $user_id) {
dd($user_id); // <-------- HERE I get TRUE instead of "2" as value.
$query->where('user_id', $user_id);
})
->when(($filter == 'paymentreceived'), function ($query) {
$query->paymentConfirmationReceived();
})
->orderBy('id', 'desc')
->paginate(50);
2
Answers
Browse: https://www.php.net/manual/en/language.references.pass.php#123995
Use like this:
The second argument that is passed to the closure, callback, is the "value". The "value" is the first argument that you pass to
when
:Since you are passing a boolean as the first argument to
when
,$value
, you are gettingtrue
in your callback as the second argument. (It has to betrue
or this callback would not have been executed)You would have to be passing
$user_id
as the first argument towhen
(the value you are checking) if you want it passed to the callback as an argument. Then, the second argument to the callback would be the value of$user_id
.Otherwise, you would have to inherit
$user_id
from the parent scope using theuse
construct (as demonstrated in the previous answer):PHP.net Manual – Anonymous Functions – Example #3