behnampmdg3's avatar

Is this the right way of deleting a record that belongs to this user?

DELETE    | users/{user}           | users.destroy    | App\Http\Controllers\UserController@destroy                            | web 
public function destroy(User $user)
    {
         $owner_id = Auth::id();
         $users = \DB::table('users')->where([
             ['owner_id', '=', $owner_id],
             ['id', '=', $user->id],
         ])->delete();
          return redirect('/users');
    }
<form action="/users/{{ $user->id }}" method="post">
     @csrf
        @method('DELETE')
         <div class="form-group">
            <input type="submit" class="btn btn-danger delete-user" value="Delete user">
        </div>
</form>
0 likes
5 replies
Tray2's avatar

That works but you can also use

public function destroy(Request $request)
{
   $user = User::findOrFail($request->id);
   $user->delete();
   return redirect('/users');
}

or

public function destroy(User $user)
{
  $user->delete();
  return redirect('/users');
}
2 likes
click's avatar

@Tray2 In your example you are missing the 'owner_id'. I would do something like:

public function destroy(User $user)
{
    // validate if the user we want to delete is owned by the currently logged in user
        // note: you could also move this permission logic to "Policies" 
    if ($user->owner_id !== Auth::id()) {
        abort(403); // throws an "Unauthorized" exception
    }

    // delete the user passed in the url
    $user->delete();

    // redirect back to the user index
    return redirect('/users');
}

Laravel Docs about policies: https://laravel.com/docs/5.7/authorization#creating-policies

1 like
click's avatar
click
Best Answer
Level 35

@behnampmdg3 not "wrong" but it could be easier like in my example above. Why a custom query builder when you already have the user object and you just use the delete() method, easier to code, easier to read.

1 like

Please or to participate in this conversation.