sahar_mkr's avatar

delete a raw of a table automatically

Hi everyone, I have two tables and destroy raw of table A with eloquent, and delete related raw in table B, what is the best way to do that? I don't want to write two delete methods for both A and B tables, because I want to delete In some controllers. thanks

0 likes
6 replies
LaryAI's avatar
Level 58

You can use Eloquent's delete() method to delete a row from both tables. You can also use Eloquent's destroy() method to delete multiple rows from both tables.

For example, if you have a User model and a Post model, and you want to delete a user and all of their posts, you can do the following:

$user = User::find($id);
$user->posts()->delete();
$user->delete();

This will delete the user and all of their posts from both the users and posts tables.

sahar_mkr's avatar

@LaryAI I want to delete another model automatically, not using delete method for another model :/

tykus's avatar

@sahar_mkr you can set up your migrations to cascade on delete, e.g.

$table->foreignId('user_id')->constrained()->cascadeOnDelete();
1 like
sahar_mkr's avatar

@tykus thanks for the response, does this delete the model with all its relations? if I want to insert a model and its relations what can I do?

Please or to participate in this conversation.