Php 显示在编辑页面上选中的复选框
我有一个编辑页面,其中有一个类别列表,与帖子有多对多的关系。看起来是这样的:Php 显示在编辑页面上选中的复选框,php,laravel,many-to-many,laravel-5.5,laravel-blade,Php,Laravel,Many To Many,Laravel 5.5,Laravel Blade,我有一个编辑页面,其中有一个类别列表,与帖子有多对多的关系。看起来是这样的: public function edit($id) { $posts = Post::find($id); $categories = Category::all(); return view('post.edit', compact('posts', 'categories')); } 我想显示在编辑页面上选择了哪一个。我有一个关于js的解决方案,但我想知道是否有可能使用lara
public function edit($id)
{
$posts = Post::find($id);
$categories = Category::all();
return view('post.edit', compact('posts', 'categories'));
}
我想显示在编辑页面上选择了哪一个。我有一个关于js的解决方案,但我想知道是否有可能使用laravel
类别本身是从数据库填充的,因此用户/管理员可以添加更多类别
控制器如下所示:
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 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
@foreach($categories作为$category)
id,$邮政分类)?'选中“:”}}>
{{$category->name}
@endforeach
希望能有帮助。。如果这个答案有任何问题,请告诉我。不幸的是,我得到了>对null上的成员函数pulk()的调用。如果得到修复,我必须稍微更改控制器上的代码,如下所示:$postCategories=$posts->Category->pulk('id')->toArray();假定关系名称为
类别
,这是laravel的默认值。。如果您有关系类别
,则会导致错误。我已经更新了答案。
@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