[Laravel] Set the initial value of the select box turned by foreach with a variable

Sep 7, 2020 PHP Laravel

Overview

For example, suppose you want to change the occupation of character A. When you press the edit button, the information of character A is displayed, and the occupation can be selected in the select box. For the contents of the select box, use foreach to display the contents of $ jobs, which is a list of occupations brought from the controller, but I want to set the initial value to warrior, which is the occupation before the change of character A.

relation

Select box

Basically, this will list “professions in the jobs table” in the select box.

<div class = "">
  <select name = "job_id">
    @foreach ($ jobs as $ job)
      <option value = "{{$ job-> id}}"> {{$ job-> name}} </ option>
    @endforeach
  </ select>
</ div>

Setting default values

Bring the character profession from the controller (The part to get the occupation list, character information, etc., and the variables to be passed that are not related to this article are omitted).

$ character_job = $ character-> job-> character_name;

return view ('character.edit')
  // Omitted
  -> with ('jobs', $ jobs)
  -> with ('character_job', $ character_job);

After that, modify the description of the select box.

<div class = "">
  <select name = "job_id">
    @foreach ($ jobs as $ job)
      @if ($ job-> name === $ character_job)
        <option value = "{{$ job-> id}}" selected = "selected"> {{$ job-> name}} </ option>
      @else
        <option value = "{{$ job-> id}}"> {{$ job-> name}} </ option>
      @endif
    @endforeach
  </ select>
</ div>

** “When the occupation of the select box matches the occupation of the character” ** selected (Although I wrote it, the setting of the occupation that appears in the article had little to do with it).