Skip to content
Advertisement

How do I delete everything related to user with the user account

I want to delete the user account as well as I want check if the user contains any 'posts', 'messages', 'friends' and if it does I want it to delete them as well.
I haven’t made any relations in their models.
I am having hard time develop this logic can anyone help me with it.

Here’s what I have done so far which dosen’t works:-

public function delete()
{
    $delete = User::find(Auth::user()->id);

    $post = DB::table('posts')
        ->where('created_by', '=', Auth::user()->uuid)
        ->get();

    $messages = DB::table('messages')
        ->where('from', '=', Auth::user()->id)
        ->where('to', '=', Auth::user()->id)
        ->get();

    $friend = DB::table('friends')
        ->where('my_id', '=', Auth::user()->id)
        ->where('friends_id', '=', Auth::user()->id)
        ->get();
  
     $delete->delete();
     $post->delete();
     $message->delete();
     $friend->delete();
}

Advertisement

Answer

get() will give you an array, so delete() may not work after you use ->get.

Try this :

$delete = User::find(Auth::user()->id);
$delete->delete(); // Example of Model

$post = DB::table('posts')
    ->where('created_by', '=', Auth::user()->uuid)
    ->delete();

$messages = DB::table('messages')
    ->where('from', '=', Auth::user()->id)
     ->where('to', '=', Auth::user()->id)
     ->delete();

$friend = DB::table('friends')
    ->where('my_id', '=', Auth::user()->id)
    ->where('friends_id', '=', Auth::user()->id)
    ->delete();
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement