显示在编辑页面上选中了哪些复选框
Show which check-boxes are checked on edit page
我有一个包含类别列表的编辑页面,这些类别与帖子具有多对多关系。它看起来像这样:
我想在编辑页面显示选择了哪一个。我有一个 js 解决方案,但想知道 laravel.
是否可行
类别本身是从数据库中填充的,因此 user/admin 可以添加更多类别。
控制器是这样的:
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');
}
和
public function post(){
return $this->belongsToMany(Post::class, 'category_post');
}
试试这个..
控制器
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
希望对您有所帮助。如果此答案有任何问题,请告诉我。
我有一个包含类别列表的编辑页面,这些类别与帖子具有多对多关系。它看起来像这样:
我想在编辑页面显示选择了哪一个。我有一个 js 解决方案,但想知道 laravel.
是否可行类别本身是从数据库中填充的,因此 user/admin 可以添加更多类别。
控制器是这样的:
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');
}
和
public function post(){
return $this->belongsToMany(Post::class, 'category_post');
}
试试这个..
控制器
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
希望对您有所帮助。如果此答案有任何问题,请告诉我。