简体   繁体   English

laravel 5.3在选择选项值中获得正确的值

[英]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 这是我在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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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