I dont know how to check old
value with pivot tables. Am building ecommerce platform and each product category can have many stores. During creation new category i select only one store and after submit sleceted store is unchecked.
What i try
<!-- Show only on update and all works good -->
@if(isset($category))
@foreach($stores as $store)
<div class="form-check">
@if($category->stores()->pluck('store.id')->contains($store->id))
<input type="checkbox" name="stores[]" checked value="{{ $store->id }}">
@else
<input type="checkbox" name="stores[]" value="{{ $store->id }}">
@endif
<label class="form-check-label" for="category_status_field">{{ $store->name }}</label>
</div>
@endforeach
@else
<!-- Show only on create -->
@foreach($stores as $store)
<div class="form-check">
<!-- Here is problem -->
<input type="checkbox" name="stores[]" {{ old('stores') == $store->categories()->pluck('category.id')->contains($store->id) ? 'checked' : '' }} value="{{ $store->id }}">
<label class="form-check-label" for="category_status_field">{{ $store->name }}</label>
</div>
@endforeach
@endif
@endif
Models
class Store extends Model
{
public function categories()
{
return $this->belongsToMany(Category::class, 'category_store', 'store_id');
}
}
class Category extends Model
{
public function stores()
{
return $this->belongsToMany(Store::class, 'category_store', 'category_id');
}
}
I also try
<input type="checkbox" name="stores[]" {{ old('stores[$store->id]') == $store->id ? 'checked' : '' }} value="{{ $store->id }}">
I dont understand how to check what checkbox is checked and with what to match to show checked
.
Thanks
2
Answers
Problem sloved
You’ve got a couple issues, the first of which is an
N+1
issue, where you’re loading every associatedstore.id
on every iteration of yourforeach()
loop. Let’s fix that first.In your Controller that renders this view, define the following:
If you’re using
Route Model Binding
, you can skip that and simply do:Now, you can reference
$storeIds
in your view. You can then use the@checked
property (available in Laravel9.x
)This will check both the
old()
values (from session redirect), or$storeIds
to see if it contains each$store->id
, and if it does, will mark the input as `checked.For reference:
@checked
Documentation