I have a select where a value needs to be selected. Select is formed using a foreach loop. I get the values correct and correct, but when I try to put this value into the session, only the last value of the cycle gets into it all the time. Why is that?
<div class="form-group"> <label for="category">Choose category</label> <select class="form-control" id="category" name="category_slug" onchange = "getSelectValue();"> @foreach($categories as $category) <option value="{{$category->slug}}">{{$category->name}}</option> {{session(['key' => $category->slug])}} @endforeach </select> @dump(session('key')) </div>
Advertisement
Answer
In your loop you overwrite the key
with each iteration so that only the last category is put into the session.
If you want to put all the categories into the session you should give each item an individual session key like this:
<select class="form-control" id="category" name="category_slug" onchange = "getSelectValue();"> @foreach($categories as $index => $category) <option value="{{$category->slug}}">{{$category->name}}</option> {{session(['category_'.$index => $category->slug])}} @endforeach </select>