Delete records with relationship in laravel

Answers 2
  • --PATH app\Http\Controllers\<YourController.php>
    $post = Post::find(1);
    Delete records with relationships in laravel is very simple as record creation. Find out the record and with the help of the delete() method deletes all the associated records. Like if you want to delete all comments related to a particular post this code snippets do it for you.
  • --PATH app\Models\Post.php
    public function comments()
        return $this->hasMany('App\Models\Comment');
    public static function boot() {
        self::deleting(function($post) { 
            $post->comments()->each(function($comment) {
    This code snippet can delete all the associated comments using the deleting event on delete a post model. Events allow you to easily execute code each time a specific model class is saved, updated or deleted in the database. To delete a model directly, call delete() on it and don't define a deleting listener in its boot method or define an empty deleting method. If you want to further delete relations of a related model, you can define a deleting listener in the boot method of that model and delete the relations there.
  • Back to code snippet queries related laravel