Brian_Kanyi's avatar

Laravel CRUD question

Hi everyone, I recently started a project that implements CRUD. I am a newbie in this framework. Below is my code .. I am using Tailwind CSS to style my views. Whenever I run this code I get an error "Undefined variable $car". What could be the problem?

View (index.blade.php) contained in a folder called cars inside views folder

<x-layout>
    @include('partials._search')
   <div class="flex mx-auto">
      <div class="grid grid-col sm:grid-cols-2 md:grid-cols-3 gap-4 mt-6 ml-6 ">
         @foreach ($cars as $car )
             <x-car-card />
         @endforeach
         
      </div>
   </div>
   <div class="mt-6 p-4">
        {{$cars->links()}}
    </div>
</x-layout>

Component car-card.blade.php contained in (/views/components/car-card.php)

@props(['car'])
 <!-- Car Details -->

<div class="h-48 w-96 bg-white rounded hover:shadow-sm hover:shadow-white duration-100">
    <div class="flex flex-row h-full">
        <img src="{{asset('images/mustung1.jpg')}}" alt="No Image" class="h-full w-1/2 bg-cover rounded-tl rounded-bl">
        <div class="inline-block p-2">
            <h1>{{$car->name}}</h1>
            <p>{{$car->horsepower}}</p>
            <p>{{$car->topspeed}}</p>
            <p>{{$car->acceleration}}</p>
            <p>{{$car->model}}</p>
            <p>{{$car->price}}</p>
            <a href="#" class=" bg-slate-400 text-white py-1 px-2 rounded">Buy</a>
        </div>
    </div>
</div>

Car Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Car;

class CarController extends Controller
{
    //Shows all cars
    public function index(){
        $cars = Car::orderBy('id','desc')->paginate(4);
        return view('cars.index', compact('cars'));
    }

    //Show create car form
    public function create(){
        return view('cars.create');
    }

    //stores car fron car_form to database 
    public function store(Request $request){
        $form_fields = $request->validate([
            'name' => 'required',
            'horsepower' => 'required',
            'topspeed' => 'required',
            'acceleration' => 'required',
            'model' => 'required',
            'price' => 'required' 
        ]);

        // $form_fields['user_id'] = auth()->id();
        
        Car::create($form_fields);
        return redirect('/')->with('message', 'Car created Successfully');
    }
    
}

Car Model Car.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Car extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'horsepower', 'topspeed', 'acceleration', 'model', 'price']; 
}

Migration create_cars_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;


return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('cars', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('car_id')->nullable()->default(0);
            $table->string('name');
            $table->integer('horsepower');
            $table->integer('topspeed');
            $table->integer('acceleration');
            $table->date('model');
            $table->decimal('price', 9, 2);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('cars');
    }
};

Routes web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
use App\Http\Controllers\CarController;
use Illuminate\Support\Facades\Auth;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/cars/index', [CarController::class, 'index'])->name('index');

Route::get('/cars/create', [CarController::class, 'create'])->name('create')->middleware('auth');

Route::post('/cars', [CarController::class, 'store'])->name('store')->middleware('auth');

My database is working fine. I can see the data in the table called cars. The problem is, I am unable to display is in the index.blade.php (/views/cars/index.blade.php). Kindly help me

0 likes
3 replies
LaryAI's avatar
Level 58

The error "Undefined variable $car" is occurring because the $car variable is not being passed to the car-card component in the index.blade.php file. To fix this, you need to pass the $car variable to the component using the "props" attribute.

Replace the line "" in the index.blade.php file with the following code:

This will pass the $car variable to the car-card component.

Also, in the car-card.blade.php file, update the "@props(['car'])" line to "@props(['car' => null])". This will set a default value of null for the $car variable in case it is not passed to the component.

Here's the updated code for the car-card.blade.php file:

@props(['car' => null])

No Image

{{$car->name}}

{{$car->horsepower}}

{{$car->topspeed}}

{{$car->acceleration}}

{{$car->model}}

{{$car->price}}

Buy

Wrap the code examples with three backticks to format them properly.

sergiosrtd's avatar
Level 7

Seems like you forgot to pass the "car" prop to the component <x-car-card />

<x-card-card :car="$car" />

1 like
Brian_Kanyi's avatar

I was able to solve the error through modifying the following in my (/views/cars/index.blade.php). It really worked for me.

@foreach ($cars as $car)
           <x-car-card :car="$car" />
  @endforeach

I passed the $car variable to the x-car-card component using the :car="$car" syntax. This ensures that the $car variable is properly initialized and accessible inside the component.

1 like

Please or to participate in this conversation.