I am using bootstrap models to add and update data. When there is no change in data while updating, livewire works fine. But it gives a blank black iframe screen when I try to update data.
Here is my code update code:
<?php
namespace App\Livewire\Admin;
use App\Models\Category as ModelsCategory;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\Title;
use Livewire\Component;
use Livewire\WithFileUploads;
#[Title('Manage Categories')]
class Category extends Component
{
use WithFileUploads;
public $categories = [], $name, $description, $image, $categoryId;
protected $rules = [
'name' => ['required', 'string', 'unique:categories,name', 'max:50'],
'description' => ['required', 'string', 'max:5000'],
'image' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:1024'],
];
protected function get(): Collection
{
return ModelsCategory::with('media')->orderByDesc('id')->get(['id', 'name', 'description']);
}
public function render()
{
$this->categories = $this->get();
return view('livewire.admin.category', ['categories' => $this->categories]);
}
public function store()
{
$validated = $this->validate();
$category = ModelsCategory::create($validated);
$category->addMedia($this->image)->toMediaCollection('images');
$this->dispatch('closeAddModel');
session()->flash('success', 'Category has been added');
}
public function edit(ModelsCategory $category)
{
$this->categoryId = $category->id;
$this->name = $category->name;
$this->description = $category->description;
$this->dispatch('openEditModel');
}
public function update()
{
$validated = $this->validate([
'name' => ['required', 'string', 'unique:categories,name,' . $this->categoryId, 'max:50'],
'description' => ['required', 'string', 'max:5000'],
]);
$category = ModelsCategory::where('id', $this->categoryId)->first();
$category->update([
'name' => $this->name,
'description' => $this->description,
]);
if ($this->image) {
$category->clearMediaCollection('images');
$category->addMedia($this->image)->toMediaCollection('images');
}
$this->reset();
$this->dispatch('closeEditModel');
session()->flash('success', 'Category has been updated');
}
}
I have used multiple methods like mass assignment. $fillable is also added. In some methods, I don't get any error but it does not update the record.
In update method, I changed
to
Don't know why but chaining update method worked.