Home >Database >Mysql Tutorial >How Can I Access External Variables in PHP Closures When Using Laravel's `where` Clauses?
Utilizing PHP Closure with External Variables
When using Laravel's advanced where clauses, it becomes necessary to pass external variables into closure functions. The default syntax involves creating a new property and accessing it through $this. However, the use keyword provides a more convenient solution.
By using use, you can declare the variables you need within the closure's scope. For instance:
DB::table('users')->where(function ($query) use ($activated) { $query->where('activated', '=', $activated); })->get();
This approach allows you to directly reference the $activated variable inside the closure.
Enhanced Syntax with PHP 7.4
In PHP 7.4, arrow functions offer a concise alternative to anonymous functions. Here's an example using arrow functions:
DB::table('users')->where(fn($query) => $query->where('activated', '=', $activated))->get();
However, keep in mind that arrow functions are slightly different from regular functions:
The above is the detailed content of How Can I Access External Variables in PHP Closures When Using Laravel's `where` Clauses?. For more information, please follow other related articles on the PHP Chinese website!