2 months ago

Checkbox query for pivot tables

Posted 2 months ago by MattB

So...I have a confusing issue I can't get my head around... I have 3 tables; news, categories, and categories_news. The pivot table is working as intended, but I have an edit page for news articles which I have a series of check-boxes pulled from the categories table. How can I enable the check-boxes to be checked if the article has those categories? (I hope that made sense).

form from blade:

<div class="col-6">
            <label for="categories">
              <strong>Choose one or more categories:</strong>
            <div class="form-group {{$errors->has('category_id') ? 'has-error' : ''}}" id="categories">   
              @foreach($categories as $category) 
              {!! Form::label('category_id[]', $category->name) !!}
              {!! Form::checkbox('category_id[]', $category->id) !!}  

edit controller:

$storySearch = News::findOrFail($id);
        $categories = categories::all();
        $newsFlashes = Newsflashes::pluck('date', 'id')->all();       
        return view('admin.stories.edit', compact('storySearch', 'categories', 'newsFlashes'));

category modal:

public function news() {
        return $this->belongsToMany(News::class);

News modal:

public function categories() 
        return $this->belongsToMany(categories::class);

Would really appreciate your help on this one please

Please sign in or create an account to participate in this conversation.