Passing Variables into Laravel Advanced Where Closures
The Laravel documentation provides an example of using whereExists with a closure to join tables:
DB::table('users') ->whereExists(function($query) { $query->select(DB::raw(1)) ->from('orders') ->whereRaw('orders.user_id = users.id'); }) ->get();
But what if you need to pass an external variable into the closure, such as a search query?
->where('city_id', '=', $this->city->id) ->where(function($query) { $query->where('name', 'LIKE', '%'.$searchQuery.'%') ->orWhere('address', 'LIKE', '%'.$searchQuery.'%') })
The current solution is to create a new property and access it using $this, but is there a more convenient way?
Yes, you can use the use keyword to pass variables from the parent scope into the closure:
DB::table('users')->where(function ($query) use ($activated) { $query->where('activated', '=', $activated); }) ->get();
In PHP 7.4, you can use the shorter arrow function syntax:
DB::table('users')->where(fn($query) => $query->where('activated', '=', $activated)) ->get();
Key differences between arrow functions and regular closures:
The above is the detailed content of How Can I Pass Variables into Laravel Advanced Where Closures?. For more information, please follow other related articles on the PHP Chinese website!