1

I have 2 tables users and user_info where the users id is used in the user_info user_id column. In order to destroy the one in the users, I used this command in Controller

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

I also had to remove the one from the user_info

$userInfo = UserInfo::findOrFail($id);
$userInfo->delete();

But I can't think of the right logic to delete the column that has the user's id and the user_info's user_id

newbie
  • 81
  • 8
  • Do you have relationship in both models? – Yasin Patel Nov 14 '19 at 07:41
  • 2
    Please look at this https://stackoverflow.com/questions/14174070/automatically-deleting-related-rows-in-laravel-eloquent-orm – Digvijay Nov 14 '19 at 07:41
  • 1
    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) – Yasin Patel Nov 14 '19 at 07:41
  • Using an event listener/observer is the way to go if you will always be deleting the `users` record via the Model – lagbox Nov 14 '19 at 07:47

3 Answers3

0

You can try

$userInfo = UserInfo::where('user_id', $id)->first()->delete();

Or if you have defined your relation userInfo() in User Model you can use (before deleting the user)

$user->userInfo->delete()
Y JRB
  • 451
  • 5
  • 14
  • 1
    I think all answers are correct but I would like to mark this as the answer because it's easy to understand for my level – newbie Nov 14 '19 at 13:30
0

Try this

$user=User::find($id);
$user_info=UserInfo::where('user_id',$id)->first();

$user->delete();
$user_info->delete();

you use first() it returns a single model, not a collection as like using find() with id where id need be primary key.

albus_severus
  • 3,626
  • 1
  • 13
  • 25
0

If you don't use Soft Deletes, then I suggest using cascade in your migration.

//secondary table
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

else, you can use the relationship to delete both records using the following logic:

$user = User::findOrFail($id);
//assuming info is defined in the user model
$user->info->delete();
//now you can delete the user
$user->delete();