Issue: A statement such as
$nb_votes = $request->input('nb_votes');
DB::table('users')
->where('name', '=', 'John')
->where(function ($query) {
$query->where('votes', '>', $nb_votes)
->orWhere('title', '=', 'Admin');
})
->get();
will return an error:
Unknown variable $nb_votes
The issue is due to the fact that $nb_votes in the anonymous function refers to the local scope, while the variable we want to use has been defined outisde of the function. We need to pass the variable to the anonymous function.
Solution: To pass a variable to an anonymous function you can do as follow:
$nb_votes = $request->input('nb_votes'); DB::table('users') ->where('name', '=', 'John') ->where(function ($query) use ( $nb_votes ) { $query->where('votes', '>', $nb_votes) ->orWhere('title', '=', 'Admin'); }) ->get();
https://www.php.net/manual/en/functions.anonymous.php
see last example in example #3
For laravel queries documentation: