You’re on the right track! In PHP, closures can "capture" variables from the parent scope using the use keyword. Here’s how you can pass your $searchText variable into the closure:
$searchText = '%john%';
$users = DB::table('users')
->where('votes', '>', 100)
->orWhere(function (Builder $query) use ($searchText) {
$query->where('name', 'like', $searchText)
->where('votes', '>', 50);
})
->get();
Explanation:
- The
use ($searchText)part makes the$searchTextvariable available inside the closure. - Now you can use
$searchTextjust like any other variable inside the function.
This is a common pattern in Laravel when you need to use external variables inside a closure for query building.