Mg Sein
Mg Sein

Reputation: 21

Cannot delete data when using sync function in laravel

I'm working on a laravel application. In laravel I'm trying to delete a row from a pivot table and it's related data. In this application I have three tables:

issues: id, title, description

categories: id, name

category_issues:(pivot table) id, issue_id, category_id

In laravel I'm trying to delete a row from a pivot table and it's related data. I have this relationships: Issue.php

public function categories() {
return $this->belongsToMany('App\Category', 'category_issues');
}

Category.php

public function issues() {
return $this->belongsToMany('App\Issue', 'category_issues');
}

A issue can have many categories.

Html code for displaying category section:

<div class="form-group row">
                    <label for="category" class="col-md-4 col-form-label text-md-right">{{ __('Category :') }}</label>
                    <div class="form-check col-md-6">
                      @foreach ($categories as $category)

                        <input type="checkbox" name="category[]" id="{{ $category->id }}" value="{{ $category->id }}"
                        {{ in_array($category->id, $issue->categories->pluck('id')->toArray())  ? 'checked' : '' }}>

                        <label for="{{ $category->id }}"> {{ $category->name }} </label>
                      @endforeach
                    </div>
                  </div>

Here is the update function file:

public function update(Issue $issue)
{
    request()->validate([
      'title'=> ['required', 'min:3'],
      'description'=> ['required', 'min:3'],
      'category' => ['required']
    ]);

    $issue->title = request('title');
    $issue->description = request('description');
    $issue->save();

    //Category_Issue Update
    $cats = request('category');
    $issue->categories()->sync($cats);

    return redirect('issues')->with('success', 'Issue has been updated');
}

Here is the delete function file:

  public function destroy(Issue $issue)
{
  $issue->categories()->delete();
  return redirect('issues')->with('danger', 'Issue deleted');
}

Upvotes: 2

Views: 1973

Answers (1)

Nazmul Abedin
Nazmul Abedin

Reputation: 157

you have to use detach(), to delete your pivot table data,

 $issue->categories()->detach();

Check this documentation https://laravel.com/docs/5.8/eloquent-relationships,

Upvotes: 1

Related Questions