How to fix Undefined variable: request in Laravel query

Sometimes you may come up with an error that says the $request variable used in the Laravel query is undefined. $request variable is used in many places in addition to Laravel queries. Let’s focus on why we get the undefined variable: request in Laravel query.

The error mostly comes up when you submit a form and try using data in the $request variable directly in a Laravel query.

As in code snippet below, we are taking the value $request->name when user submits a form. We are then using it to compare the value in the database to match userName to get the data. In cases like these, you may get an Undefined variable: request error.

Undefined Variable Example Cases

Case 1:

if($request->name != '') {
    $query->where(function ($query) {
    $query->where('userName', $request->name)
            ->orWhere('userName', 'alice');

A solution to this can be to add use($request) before defining the function, as shown in the code snippet below.

if($request->name != '') {
    $query->where(function ($query) use($request) { // <-- without use, your 
      $query->where('userName', $request->name)     //     anonymous function
            ->orWhere('userName', 'alice');              //     cannot access $request

Case 2:

In the example below, we try to use $id that comes from a URL. For example, . We then define a route for above URL as, Route::get(‘/cars/{$id}’, CarsController@carsIndex);

class CarsController extends Controller
   public function carsIndex($id, $slug) {
   // echo $id works without a problem

   $findPlate = Thing::with(array('plate' => function($query) use ($id) {
        $query->where('imageable_type', 'App\Models\Thing')
              ->where('imageable_id', $id);

        $mainPlate = $findPlate->plate;

Similarly, in this case too, adding use($id) makes it work well, or else the variable is anonymous to function($query).

The error may come up on the $request variable that reads multiple data items or on a single entity, as the $id in the example above. The approach is to add the undefined variable in a use() function, so it is always used in the function as a defined variable.,

Leave a Comment