laravel 5.3在select option value中获取正确的值

时间:2017-02-01 22:43:56

标签: php laravel-5.3

在我的编辑表单中,select选项值没有从db填充正确的值。

我有两个有一对多关系的模特。艺术家和专辑

这是我在albumcontroller中的编辑方法

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

这是填充选择选项的代码

 <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>

此代码填充了数据库中的所有艺术家,但没有为该专辑选择匹配的艺术家。

2 个答案:

答案 0 :(得分:0)

编辑功能:

public function edit($id)
{

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

形式:

<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>

答案 1 :(得分:0)

$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'));

 <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>