我有一个包含类别列表的编辑页面,这些类别与帖子有多对多的关系。它看起来像这样:
我想显示在编辑页面中选择了哪一个。我有一个js的解决方案,但想知道laravel是否可行。
类别本身是从数据库填充的,因此用户/管理员可以添加更多类别。
控制器就像这样:
adb shell settings put global development_settings_enabled 0
adb shell pm clear com.android.settings
adb shell am force-stop com.android.settings
和视图:
public function edit($id)
{
$posts = Post::find($id);
$categories = Category::all();
return view('post.edit', compact('posts', 'categories'));
}
关系
<div class="category section">
<h4>Categories</h4>
<div class="checkbox">
<ul>
@foreach( $categories as $category)
<li>
<input type="checkbox" name="category[]" value="{{ $category->id }}" id="{{ $category->id }}">
<label for="{{ $category->id }}">{{ $category->name}}</label>
</li>
@endforeach
</ul>
<a href="/categories/create" target="_blank">Shto Kategori</a>
</div>
</div>
和
public function category(){
return $this->belongsToMany(Category::class, 'category_post');
}
答案 0 :(得分:0)
试试这个..
<强>控制器强>
public function edit($id)
{
$postCategories = [];
$posts = Post::find($id);
$postCategories = $posts->category->pluck('id')->toArray();
$categories = Category::all();
return view('post.edit', compact('posts', 'categories', 'postCategories'));
}
查看强>
@foreach( $categories as $category)
<li>
<input type="checkbox" name="category[]" value="{{ $category->id }}" id="{{ $category->id }}" {{ in_array($category->id, $postCategories) ? 'checked' : '' }}>
<label for="{{ $category->id }}">{{ $category->name}}</label>
</li>
@endforeach
希望它有所帮助..如果对此答案有任何疑问,请告诉我..