Search code examples
mysqllaravelmodelsdelete-row

Laravel delete in two related tables in the same time


I'm trying to delete data in two related tables between themselves. So, when I delete a row in websites table, I also want to delete rows in keywords table which are related with foreign key

websites
id | siteName

1 | example

keywords
id | website_id | kwName

1 | 1

So when I delete a website, the row with the same id(website_id as foreign key) does not deleted.

My code for delete is:
Controller

public function destroy($id)
{ 
     $projects = Website::findOrFail($id);
     $projects->delete();

    return redirect()->route('projects.index')->with('alert-success','Data Has been Deleted!');
}

Blade

@foreach($projectss as $projects)

    <tr>

      <td>{{$no++}}</td>
      <td>{{$projects->siteName}}</td>
      <td>{{$projects->siteUrl}}</td>       


      <td>
        <form class="" action="{{route('projects.destroy',$projects->id)}}" method="post" enctype="multipart/form-data">
          <input type="hidden" name="_method" value="delete">
          <input type="hidden" name="_token" value="{{ csrf_token() }}">
          <a href="{{route('projects.show',$projects->id)}}" class="btn btn-success">View</a>
          <a href="{{route('projects.edit',$projects->id)}}" class="btn btn-primary">Edit</a>
          <input type="submit" class="btn btn-danger" onclick="return confirm('Are you sure to delete this data');" name="name" value="delete">
        </form>
      </td>
    </tr>
  @endforeach

Model Keyword.php

public function website() {
    return $this->belongsTo('App\Website');
}

Model Website.php

public function keywords() {
    return $this->hasMany('App\Keyword');
}

Solution

  • One quick method you can utilize us to bind to the boot function in your Website model and then capture the deleted event, which provides you an instance of the model that is being deleted as the first argument ($website).

    Here's an example:

    public static function boot()
    {
        parent::boot();
    
        static::deleted(function($website){
            $website->keywords()->delete();
        });
    }