简体   繁体   中英

laravel 5.3 getting correct value in select option value

in my edit form select option value is not populating correct value from db.

ihave two models having one to many relationship. artist and album

this is my edit method in albumcontroller

 public function edit($id)
    {
        //
        $album = Album::find($id);
        $artists = Artist::all();
        return view('admin.albums.edit', compact('album', 'artists'));
    }

and this is the code populating select option

 <div class="form-group">
                    <label for="artist">Select An Artist:</label>
                    <select class="form-control" id="Artist" name="artist_id">
                        @foreach($artists as $artist)
                            <option value="{{$artist->id}}">{{ $artist->name }}</option>
                        @endforeach
                    </select>
                </div>

this code is populating all the artists in the db but not selecting the matching one for that album.

Edit function:

public function edit($id)
{

    $album = Album::find($id);
    $artists = Artist::all();
    $current_artist = $album->artist()->first();
    return view('admin.albums.edit', compact('album', 'artists'));
}

Form:

<div class="form-group">
<label for="artist">Select An Artist:</label>
<select class="form-control" id="Artist" name="artist_id">
    @foreach($artists as $artist)
        <option value="{{$artist->id}}"@if($artist->id == $current_artist->id) selected='selected' @endif>{{ $artist->name }}</option>
    @endforeach
</select>
</div>
$album = Album::find($id);
$artist = $album->artist()->first();
$artist_id = $artist ? $artist->id : 0;
$artists = Artist::all();

return view('admin.albums.edit', compact('artist_id', 'artists'));

and

 <div class="form-group">
    <label for="artist">Select An Artist:</label>
    <select class="form-control" id="Artist" name="artist_id">
        @foreach($artists as $artist)
            <option {{ $artist_id === $artist->id ? 'selected' : '' }} value="{{$artist->id}}">{{ $artist->name }}</option>
        @endforeach
    </select>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM