Passing Variables into Laravel's Advanced Where Closures
Laravel's advanced where functions provide powerful ways to filter your queries. However, you may encounter situations where you need to pass external variables into the closure used in the where function.
Example Scenario
Suppose you want to use an external variable, such as $searchQuery, in your where closure:
->where('city_id', '=', $this->city->id) ->where(function($query) { $query->where('name', 'LIKE', '%'.$searchQuery.'%') ->orWhere('address', 'LIKE', '%'.$searchQuery.'%') })
Use Keyword Solution
You can pass the necessary variables into the closure using the use keyword:
DB::table('users')->where(function ($query) use ($searchQuery) { $query->where('name', 'LIKE', '%'.$searchQuery.'%') ->orWhere('address', 'LIKE', '%'.$searchQuery.'%') })->get();
PHP 7.4 Arrow Function (Update)
In PHP 7.4 and later, you can use arrow functions for a more concise syntax:
DB::table('users')->where(fn($query) => $query->where('name', 'LIKE', '%'.$searchQuery.'%') ->orWhere('address', 'LIKE', '%'.$searchQuery.'%'))->get();
Unlike regular anonymous functions, arrow functions automatically capture variables from the parent scope and do not allow explicit listing via use. However, they must have a single return statement and cannot contain multiple lines of code.
The above is the detailed content of How Can I Pass Variables to Laravel's Advanced Where Closures?. For more information, please follow other related articles on the PHP Chinese website!