【问题标题】:Show which check-boxes are checked on edit page显示在编辑页面上选中了哪些复选框
【发布时间】:2018-04-19 08:01:37
【问题描述】:

我有一个包含类别列表的编辑页面,这些类别与帖子具有多对多的关系。它看起来像这样:

我想显示在编辑页面上选择了哪一个。我有一个 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 category(){
    return $this->belongsToMany(Category::class, 'category_post');
}

public function post(){
    return $this->belongsToMany(Post::class, 'category_post');
}

【问题讨论】:

    标签: php laravel many-to-many laravel-5.5 laravel-blade


    【解决方案1】:

    试试这个..

    控制器

    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
    

    希望对您有所帮助..如果此答案有任何问题,请告诉我..

    【讨论】:

    • 不幸的是,我得到 > 在 null 上调用成员函数 pluck()
    • 修复了它,我不得不稍微更改控制器上的代码,如下所示: $postCategories = $posts->Category->pluck('id')->toArray();
    • 假定关系名称为 categories,这是 laravel 的默认值。如果你有关系 category,这会导致错误。我已经更新了答案。
    猜你喜欢
    • 1970-01-01
    • 2021-12-17
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2016-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多