Laravel old values plus newly checked values in edit template

Viewed 38

In my edit.blade, I would like to show categories that were checked before by user + user can check new categories. So if a validation error occurred, the newly checked categories do not become unchecked.

This is what I have now:

@foreach($categories as $category)
    <input type="checkbox" id="category_id" name="category_id[]" value="{{ $category->id }}"
    {{ $category->posts->contains($post->id) ? 'checked' : '' }}
    @if (old('category')==$category->id) ? 'checked' : '' @endif>
    <label for="{{$category->id}}"> {{$category->category_name}}</label>
@endforeach

How can I do it?

1 Answers

put the previously selected items in an array in controller and pass it to the view. like

$previouslySelected = [1, 3, 5];

and then you use the old helper to show the selected options.

<input type="checkbox" name="category_id[]" value="{{ $category->id }}"
class="form-check-input" id="category{{ $category->id }}"
@if (in_array($category->id, old('category_id', $previouslySelected ))) checked @endif>

this will first check the values in $previouslySelected array. and when the validation fails, will check the values from old values.

Related