Furya
Furya

Reputation: 463

Laravel 5.4 delete one to many relationship

I want to delete a record on a table if no one use it on another.

For example, if I delete all articles in a category, I want to delete this category too because no one use it.

Is there a simple way to do it with laravel ?

Thank

Upvotes: 0

Views: 73

Answers (2)

user7747472
user7747472

Reputation: 1952

Use laravel doesntHave method to delete all categories that doesn't have articles.

Something like this

category::doesntHave('articles')->delete();

You can read more about this in the official document here

Upvotes: 1

Bryan Miller
Bryan Miller

Reputation: 3323

When you check to see if a category has any articles, you can just delete the category if there aren't any. For example:

if(!$category->articles->count()){
   $category->delete();
}

Upvotes: 0

Related Questions