Search code examples
phplaravellaravel-livewire

Property [id] does not exist on the Eloquent builder instance in Laravel 8 and Livewire 2.7


My users can create multiple usercar's when selecting from a database of car's. I need to grab the selected car values, but when I dd the values, I get a Property [id] does not exist on the Eloquent builder instance. error. wire:model="car_id" is the select input value used in the code below.

AddUserCar.php

...
class AddUserCar extends Component
{
    public $showAnotherModel = false;

    // Steps
    public $totalSteps = 8;
    public $step = 1;
    // User
    public $super;
    public $first_name;
    public $last_name;
    public $email;
    public $status = 1;
    public $role = 'Driver';
    // Usercar
    public $car_id;
    public $calc_date;
    public $year;
    public $model;
    // Form Function
    public $car_year;

    //public $cars;
    //public $modelId;

    ...

    public function moveAhead()
    {

        if($this->step == 1) {
            $newCar = Car::where('id', '=', $this->car_id)->get();
            dd($newCar->id); // This is where I get error

            $this->usercarCreated = Usercar::create([
                'year' => $newCar->start_year,
                'model' => $newCar->model,

                'car_id' => $this->car_id,
                'user_id' => Auth::user()->id,
                'tenant_id' => Auth::user()->tenant_id,
                'calc_date' => now()->format('m-d-Y'),
            ]);

            $this->resetErrorBag();
            $this->resetValidation();
        }

        ...

    public function render()
    {
        return view('livewire.add-user-car',
        ['pageTitle' => 'Add Driver Car']);
    }
}

Solution

  • Use ->get() to retrieving all rows from a table :

    $cars = Car::where('id', '=', $this->car_id)->get();
    
    foreach($cars as $car){
        echo $car->id;
    }
    
    // ERROR, because $cars isn't a single row
    dd($cars->id);
    

    Use ->first() to retrieving a single row / column from a table.

    $car = Car::where('id', '=', $this->car_id)->first();
    // or 
    $car = Car::find($this->car_id);
    
    // WORK
    dd($car->id);