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.
To do that, you have to use a model that exists in the database.
@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.
@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;
}
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.
@ahuman great but any idea if they will drop the support at some point. The term Legacy feel like it.
@arifhossen what is the proper way to handle data binding then?
@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"
@arifhossen this is giving me a carry is null error. not working
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.
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',
];
Please or to participate in this conversation.