earmsby's avatar

pass value into compound where clause

I'm trying to modify slightly the example given in the Laravel docs for grouped where statements. The code in the docs is:

use Illuminate\Database\Query\Builder;

$users = DB::table('users') ->where('votes', '>', 100) ->orWhere(function (Builder $query) { $query->where('name', 'Abigail') ->where('votes', '>', 50); }) ->get();

In the example, hard-coded values are used for the orWhere clause. How can I pass in a variable like:

$query->where('name','like',$searchText)

I tried setting the value before the $users=DB::table('users')->etc statement but it's available instead the function. I also tried adding it as a parameter on the function but that didn't work either.

I'm probably missing something obvious.

0 likes
2 replies
LaryAI's avatar

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 $searchText variable available inside the closure.
  • Now you can use $searchText just 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.

1 like
martinbean's avatar

@earmsby You’ll need to pass the value in the closure:

  use Illuminate\Database\Query\Builder;

+ $name = 'Abigail';

  $users = DB::table('users')
      ->where('votes', '>', 100)
-     ->orWhere(function (Builder $query) {
-         $query->where('name', 'Abigail')->where('votes', '>', 50);
+     ->orWhere(function (Builder $query) use ($name) {
+         $query->where('name', $name)->where('votes', '>', 50);
      })
      ->get();

Please or to participate in this conversation.