arifhossen's avatar

Eloquent model binding to a Livewire component property

Hi there, In Livewire 2 we were mount model like this:

	public $order;

    public function mount(Order $order)
    {
        $this->order = $order;
    }

but when I tried it in Livewire 3 it show an error: -

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

Please help me to replace this code and find a new way to handling it.

0 likes
11 replies
vincent15000's avatar

To do that, you have to use a model that exists in the database.

arifhossen's avatar

@vincent15000 Thank you for your valuable reply. My application is in production for almost 2 years. I am trying to upgrade Livewire version 2 to 3.

Happy coding.

2 likes
vincent15000's avatar

@ahuman I've had the same problem as you when I have upgrades my application from Livewire 2 to 3.

Here is what I have done and it works.

class IngredientsFormPage extends Component
{
    public Recipe $recipe;

    public function mount(Recipe $recipe)
    {
        $this->recipe = $recipe;
    }
arifhossen's avatar
arifhossen
OP
Best Answer
Level 21

In Livewire 3, binding directly to Eloquent models has been disabled

Version 3 maintains support for this behaviour via a configuration item in config/livewire.php

'legacy_model_binding' => true,

By setting legacy_model_binding to true, Livewire will handle Eloquent model properties exactly as it did in version 2.

3 likes
MathieuB's avatar

@ahuman great but any idea if they will drop the support at some point. The term Legacy feel like it.

2 likes
arifhossen's avatar

@wishborn I prefer the Laravel way.

	public $order;

    public function mount(Order $order)
    {
        $this->order = $order;
    }

Then you can access {{ $order }} model instance.

To handle livewire model input wire:model="order.id"

all1.ai's avatar

Enabling legacy_model_binding doesn't work for me either. It is still null on the view side when you bind it. Been messing with it for hours.

mikitu's avatar

Add 'legacy_model_binding' => true to config/livewire.php and add validation rule for the field you want to link with wire:model. For example

protected $rules = [
    'user.age' => 'nullable|integer|min:1|max:80',
];
2 likes

Please or to participate in this conversation.