2 回答

TA貢獻1934條經(jīng)驗 獲得超2個贊
在 HTML 表單上,您可以檢查是否id是這樣的一部分$post(我會做最容易理解的,您可以通過多種方式進行重構(gòu)):
<option value="{{ $category->id }}" {{isset($post->categories->where('id', $category->id)->first())?'selected':''}}>{{ $category->name}}</option>
為了使這件事變得簡單并以最少的調(diào)用數(shù)據(jù)庫,在刀片視圖上的循環(huán)之前將類別關(guān)系加載到您的帖子中。您不需要 ( $post=Post::find($post->id);) 行,因為您的路由模型綁定已經(jīng)注入了它。
在您的Controller的edit方法中:
public function edit(Post $post)
{
$post->load('categories');
$categories=Category::all();
return view('admin.pages.post.edit',compact('post','categories'));
}
我假設(shè)你有關(guān)系,從categories到posts您的正確設(shè)置后的模型。但這本質(zhì)上只是詢問“此表單上的此帖子是否具有此類別(按此循環(huán)),然后將其標(biāo)記為已選中”。
我真的很喜歡 LaravelCollective 的方式來做到這一點,也推薦你看看圖書館。它將模型綁定到表單,并自動為您選擇所選項目。您可以使用 Collective 在這樣的簡單行中完成:
{!! Form::select('categories[]', $categories, null, ['class'=>'form-control', 'multiple', 'id'=>'categories']) !!}

TA貢獻1836條經(jīng)驗 獲得超3個贊
修復(fù)了數(shù)小時搜索后的問題
在我所做的編輯方法中:
public function edit(Post $post)
{
$post=Post::with('tags','categories')->find($post->id);
$tags=Tag::all();
$categories=Category::all();
return view('admin.pages.post.edit',compact('post','categories','tags'));
}
在我看來:
<div class="form-group">
<label>Categories</label>
<select class="form-control" id="categories" name="categories[]" multiple="multiple">
@foreach($categories as $category)
<option value="{{ $category->id }}"
@foreach($post->categories as $postCat)
{{ $postCat->id==$category->id?'Selected':'' }}
@endforeach
>{{ $category->name}}</option>
@endforeach
</select>
- 2 回答
- 0 關(guān)注
- 212 瀏覽
添加回答
舉報