Delete records with relationship in laravel

Created at 20-Mar-2021 , By samar

Delete records with relationship in laravel

Good day, guys. In this post, we’ll look at how to solve the "Delete records with relationship in laravel" programming puzzle.

  • --PATH app\Http\Controllers\<YourController.php>
    $post = Post::find(1);
    $post->comments()->delete();
    
    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() {
        parent::boot();
        self::deleting(function($post) { 
            $post->comments()->each(function($comment) {
                $comment->delete(); 
            });
        });
    }
    
    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

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.