skip to Main Content

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


  1. Browse: https://www.php.net/manual/en/language.references.pass.php#123995

    Use like this:

    $user_id = 2;
    
    $orders = Order::with('user')
        ->when(!empty($user_id), function ($query) use ($user_id) {
            $query->where('user_id', $user_id);
        })
        ->when(($filter == 'paymentreceived'), function ($query) {
            $query->paymentConfirmationReceived();
        })
        ->orderBy('id', 'desc')
        ->paginate(50);
    
    Login or Signup to reply.
  2. The second argument that is passed to the closure, callback, is the "value". The "value" is the first argument that you pass to when:

    public function when($value = null, callable $callback = null, callable $default = null)
    {
        ...
        return $callback($this, $value) ?? $this;
        ...
    }
    

    Since you are passing a boolean as the first argument to when, $value, you are getting true in your callback as the second argument. (It has to be true or this callback would not have been executed)

    You would have to be passing $user_id as the first argument to when (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.

    ...->when($user_id, function ($builder, $user_id) { ... })
    

    Otherwise, you would have to inherit $user_id from the parent scope using the use construct (as demonstrated in the previous answer):

    ...->when(..., function ($builder) use ($user_id) { ... })
    

    PHP.net Manual – Anonymous FunctionsExample #3

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search