Search code examples
phplaravellaravel-livewire

Laravel Livewire V3 Can't set model as property if it hasn't been persisted yet


I updated one of my projects to Laravel Livewire V3 and am running into a few snags. Most of my routes are working fine, but there are a few that for some reason are throwing the error Can't set model as property if it hasn't been persisted yet and for the life of me, I can't figure it out. I am having no issues with most of my routes--it's just a random few, like the route below.

web.php

...
Route::get('/evaluation/{evaluation}/edit', App\Livewire\Evaluations\Edit::class)->middleware(IsAdminMiddleware::class)->name('evaluation.edit');
...

Edit.php

<?php

namespace App\Livewire\Evaluations;

use App\Models\Evaluation;
use App\Models\Farm;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Livewire\Component;

class Edit extends Component
{
    public $user, $farm, $evaluation, ...;

    public function mount(User $user, Evaluation $evaluation, Farm $farm) {
        $this->user = $user;
        $this->farm = $farm;
        $this->evaluation = $evaluation;
        $this->farm_id = $evaluation->farm_id;
        $this->user_id = $evaluation->user_id;
        ...
    }
...

Evaluation.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Evaluation extends Model
{
    protected $guarded = [];
    use SoftDeletes;


    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function farm()
    {
        return $this->belongsTo(Farm::class, 'farm_id');
    }
...

Solution

  • Would you try to update livewire config (config/livewire.php):

    [
       ...,
       legacy_model_binding => true
    
    ]