What seems to be the problem: When I want to edit a product, it opens a modal where the data of that product is loaded, but where I have a select where it should show by default the category that that product had, it always shows the first entry of the options that the select has.
The strange thing is that when I inspect the code I can see that it has the property “selected” in the category that corresponds to it, however in the modal it always shows the first option.
Code:
livewire view: show-products.blade.php
show-products.blade.php
`
@foreach ($products as $product)
{{$product->idProduct}}
{{$product->prdName}}
@livewire(‘edit-product’, [‘product’ => $product], key($product->idProduct))
@endforeach `
livewire view: edit-product.blade.php
edit-product.blade.php
`
<x-jet-dialog-modal wire:model="open">
<x-slot name="title">
Edit product
</x-slot>
<x-slot name="content">
...
<div>
<select name="idCategory" class="form-control" wire:model="idCategory">
@foreach ($categories as $category)
<option @if ($product->idCategory == $category->idCategory) selected @endif
value="{{ $category->idCategory }}" >
{{ $category->name }}
</option>
@endforeach
</select>
</div>
...
</x-slot>
<x-slot name="footer">
<x-jet-secondary-button wire:click="$set('open', false)">
Cancel
</x-jet-secondary-button>
<x-jet-danger-button wire:click="save" wire:loading.attr="disabled" class="disabled:opacity-25">
Update
</x-jet-danger-button>
</x-slot>
</x-jet-dialog-modal>
`
Livewire component: EditProduct.php
EditProduct.php
`
<?php
namespace App\Http\Livewire;
use App\Models\Category;
use App\Models\Product;
use Livewire\Component;
class EditProduct extends Component
{
public $open = false;
public $product, $prdName, $idCategory;
protected $rules = [
'product.prdName' =>'required|min:2|max:30',
'product.idCategories' =>'required|numeric',
];
public function mount(Product $product)
{
$this->product = $product;
}
public function save()
{
$this->validate();
$this->product->save();
$this->reset();
$this->emitTo('show-products','render');
$this->emit('alert', 'Product updated');
}
public function render()
{
$categories = Category::all();
return view('livewire.edit-product', compact('categories'));
}
}
`