0
votes

I keep getting Undefined variable: cars when loading the page in Laravel.

I have the following code:

web.php

Route::get('/cars', function () {
    $cars= Car::select('brand')->get();    
    return view('test.cars')->with(compact($cars));
});

If I put dd(cars); before return view the collection is outputted.

In cars.blade.php I have the following code:

<select name="car">
@foreach($cars as $car)
    <option>{{ $car->brand}}</option>
@endforeach
</select>

and I get Undefined variable: cars, I also removed the dropdown from blade template and I tried {{ dd($cars) }} but get the same error.

2

2 Answers

0
votes

Try the below code :

Route::get('/cars', function () {
    $cars= App\Car::pluck('brand');    
    return view('test.cars',['cars'=>$cars]);
});

OR

Route::get('/cars', function () {
    $cars= App\student::pluck('first_name');    
    return view('test.cars', compact('cars'));
});

Note: Car model is present in App folder here.

0
votes

The correct syntax for passing variables to views is either:

view('test.cars', ['cars' => $cars])

or

view('test.cars')->with('cars', $cars)

the "with" function requires a name to be passed first, followed by the variable.