'Use identifier in PHP and how does it affect the logic

Use identifier is used when we want to send some outer environment variables inside closures so I have a scenario.

$invoiceList = UserInvoice::where('user_id', $this->user->id)
            ->where(function ($query) use ($filters) {
                $query->where('invoice_number', 'LIKE', "%{$filters['invoiceNumber']}%")
                    ->when($filters['type'], function ($query) use ($filters) {
                        $query->whereIn('invoice_type', $filters['type']);
                    });
            });

In this Laravel eloquent query I have checked for filter['type'] when it is there then try to filter my invoice_type from filter[type]

But I am now confused here that what if I pass filters inside functions parameters like this

method 1 

->when($filters['type'], function ($query,$filters) use () {
                        $query->whereIn('invoice_type', $filters['type']);
                    });

Or

method 2 

->when($filters['type'], function () use ($query,$filters) {
                        $query->whereIn('invoice_type', $filters['type']);
                    });

What impact would it be if I opt these methods I have also tried both and in method 1 it throws me an error that filters['type'] not available and when I tried method 2 it works fine so please can any one explain how does it works I mean not theoretically but in practical language what basically happening there. Also where it is defined that a closure function will accept how many numbers of arguments



Solution 1:[1]

The very last thought in your question is actually the key to your misunderstanding:

where it is defined that a closure function will accept how many numbers of arguments

The answer is wherever the function is eventually executed.

In this case, you are passing the function to the when method; that method can decide when to execute it, and what parameters to pass when it does. We can look at the source code directly and see what happens:

public function when($value, callable $callback = null, callable $default = null)
{
    // some extra logic skipped as not relevant right now

    if ($value) {
        return $callback($this, $value) ?? $this;
    } elseif ($default) {
        return $default($this, $value) ?? $this;
    }

    return $this;
}

So, if $value is "truthy", $callback will be executed with exactly two parameters: the current object ($this) and the exact value provided ($value). In this case, that will be the query you're building, and the value of $filters['type'].

Think of it like handing over an envelope: you don't have any control of what the when method puts into the envelope, you just get to look at it once it's there.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 IMSoP