1

I have a Post table with the following fields (id, name, state_id, city_id, category_id, subcategory_id) and PostPhoto table with the following fields (id, photo_url, post_id)

The Post Model has

public function user(){
        return $this->belongsTo(User::class);
    }
    public function category(){
        return $this->belongsTo(Category::class);
    }
    public function subCategory(){
        return $this->hasOne(SubCategory::class);
    }
    public function photos(){
        return $this->hasMany(PostPhoto::class);
    }
    public function city(){
        return $this->belongsTo(City::class);
    } 

and PostPhoto Model has

 public function post()
    {
        return $this->belongsTo(Post::class);
    }

Now if I want to delete a particular post, it'll fail due to foreign key constrains. How do I delete the Post together with postphotos associated with it completely from database. And each post can have multiple photos also. Please any suggestion will be appreciated. Thanks

  • Does this answer your question? [Automatically deleting related rows in Laravel (Eloquent ORM)](https://stackoverflow.com/questions/14174070/automatically-deleting-related-rows-in-laravel-eloquent-orm) – Worthwelle Nov 05 '20 at 07:46

2 Answers2

1

In your Post model add booted method .boot method will call whenever model executes.if you are calling post delete then static deleting closure will exicutes

if you are using latest larvel 8

 protected static function booted()
 {
      static::deleting(function($post) { 
             $post->photos()->delete();
            
        });
  }

if you are using older laravel version then

protected static function boot()
    {
        parent::boot();

        static::deleting(function($post) { 
                 $post->photos()->delete();
                
            });
    }

Update

$post=Post::find($id);
$post->photos()->delete();
$post->delete();
Vision Coderz
  • 8,257
  • 5
  • 41
  • 57
1

Either you can make post_id as a foreign key and make cascade relation on update and delete which will automatically delete post photos on post deletion.

otherwise, you can try below code.

try {
   \DB::beginTrasaction();
    PostPhotos::where('post_id', 'your-post-id')->delete();
    Post::where('id', 'your-post-id')->delete();
   \DB::commit();
} catch(\Exception $exception) {
   \DB::rollback();
}
Jitender Thakur
  • 490
  • 5
  • 15