Hello,
I'm testing the Laravel 3 features.
I'm trying to set a custom property type.
https://livewire.laravel.com/docs/properties
Here is the model and the controller.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Livewire\Wireable;
class Category extends Model implements Wireable
{
use HasFactory;
protected $fillable = [
'name',
];
protected $name;
public function __construct($name = null)
{
$this->name = $name;
}
public function toLivewire()
{
return [
'name' => $this->name,
];
}
public static function fromLivewire($data)
{
$name = $data['name'];
return new static($name);
}
public function recipes()
{
return $this->hasMany(Recipe::class);
}
}
<?php
namespace App\Livewire\Pages;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
use Livewire\WithPagination;
use App\Models\Category;
use App\Traits\TrimStringAndSetNullIfEmptyString;
class Categories extends Component
{
use WithPagination;
use AuthorizesRequests;
use TrimStringAndSetNullIfEmptyString;
public Category $category;
public $updateMode = false;
public $showModal = false;
public $fieldsToClean = [
'category' => [
'name',
],
];
public function paginationView()
{
return 'utils.pagination-links-view';
}
public function mount()
{
$this->category = new Category;
}
public function initForm()
{
$this->updateMode = false;
$this->category = new Category;
}
public function updatedCategory()
{
if ($this->updateMode == false) {
$this->resetPage();
}
}
public function save()
{
$this->cleanFields();
$this->validate();
$this->showModal = false;
if ($this->updateMode) {
$this->authorize('update', $this->category);
$this->category->update();
} else {
$this->authorize('create', Category::class);
$this->category->save();
}
$this->initForm();
}
public function edit($id)
{
$this->updateMode = true;
$this->showModal = true;
$this->category = Category::find($id);
}
public function cancel()
{
$this->showModal = false;
$this->initForm();
}
public function render()
{
$categories = Category::
withCount('recipes')
->when($this->category->name, function ($query) {
$query->where('name', 'like', '%'.$this->category->name.'%');
})
->orderBy('name')
->paginate(10);
return view('livewire.pages.categories', compact('categories'));
}
}
It works fine with Livewire 2, but not with Livewire 3 for which I get this error.
Can't set model as property if it hasn't been persisted yet
What happens ?
Thanks for your help.
V