代码之家  ›  专栏  ›  技术社区  ›  key Austin HLYO

显示在编辑页面上选中的复选框

  •  0
  • key Austin HLYO  · 技术社区  · 6 年前

    我有一个目录列表的编辑页面,它与帖子有着多对多的关系。看起来是这样的:

    enter image description here

    我想显示在编辑页面上选择了哪一个。我对js有一个解决方案,但我想知道是否可以使用laravel。

    enter image description here

    类别本身是从数据库填充的,因此用户/管理员可以添加更多类别。

    控制器如下所示:

        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');
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   iamab.in    6 年前

    试试这个。。

    控制器

    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
    

    希望有帮助。。如果这个答案有任何问题,请告诉我。。