Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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');
}
like image 597
R.Jonson Avatar asked Jan 25 '26 16:01

R.Jonson


2 Answers

The best way to achieve this is to use onDelete('cascade') when defining foreign key constraint:

$table->foreign('website_id')->references('id')->on('websites')->onDelete('cascade');

So when you'll delete a website, all keywords related to it will be deleted automatically.

https://laravel.com/docs/5.4/migrations#foreign-key-constraints

like image 100
Alexey Mezenin Avatar answered Jan 27 '26 08:01

Alexey Mezenin


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();
    });
}
like image 22
Ohgodwhy Avatar answered Jan 27 '26 07:01

Ohgodwhy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!