Phú
Phú

Reputation: 25

Old value in multiple select option in laravel

Here is my select option

 <select name="category[]" id="categories"
class="js-example-basic-single form-control"multiple>
@foreach ($category as $element)
<option value=" {{$element->id}}}"{{ (old("category[]") == $element->id ? "selected":"") }}>
{{$element->name}}
</option>
 @endforeach

  </select>

I can't get the old value ,What I'm doing wrong? how can i get the old value ? thanks.

Upvotes: 0

Views: 1814

Answers (3)

Kamlesh Paul
Kamlesh Paul

Reputation: 12401

you can try in_array()
https://www.w3schools.com/php/func_array_in_array.asp

<select name="category[]" id="categories" class="js-example-basic-single form-control" multiple>
    @foreach ($category as $element)
    <option value=" {{$element->id}}}" {{  in_array($element->id ,old("category",[]) ? "selected":"") }}>
        {{$element->name}}
    </option>
    @endforeach
</select>

Upvotes: 0

You could try the following code:

<select name="category[]" id="categories" class="js-example-basic-single form-control"multiple>
    @foreach ($category as $element)
      <option value=" {{$element->id}} " {{ (collect(old('category'))->contains($element->id)) ? 'selected':'' }}>{{ $element->name }}</option>
    @endforeach
    
</select>

Upvotes: 0

lagbox
lagbox

Reputation: 50541

The variable is not named category[] on the server side, that is just notation to turn it into an array; it is named category.

As Kamlesh Paul has stated you can use in_array to check against the possible values of the old input array:

{{ in_array($element->id, (array) old('category', [])) ? "selected" : "" }}

Upvotes: 1

Related Questions