Search code examples
phplaravelmany-to-manylaravel-5.5laravel-blade

Show which check-boxes are checked on edit page


I have this edit page with a list of categories, which have a many-to-many relationship with posts. It looks like this:

enter image description here

I want to show which one are selected at the edit page. I have a solution with js, but want to know if it is possible with laravel.

enter image description here

The categories itself are populated from the database, so a user/admin can add more categories.

The controller is just like this:

    public function edit($id)
{
    $posts = Post::find($id);
    $categories = Category::all();

    return view('post.edit', compact('posts', 'categories'));
}

and the view:

<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>

The Relationships

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

and

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

Solution

  • Try this..

    Controller

    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'));
    }
    

    View

    @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
    

    Hope it helps.. Let me know if any problem with this answer..