Skip to content
Advertisement

Best way of deleting multiple records linked in different tables in Laravel query builder

I’ve got a function in my Laravel 8 API that deletes a user’s account, it also deletes any of data in any other table where their user_id matches the one of the account that’s being deleted. One thing has become apparant quite quickly with this, is how can this be scaled, and whether there’s a better, potentially faster and more reliable way to delete linked tables data.

On the other hand, am I doing it the way that would be fine for medium sizes web applications, my current code is:

/**
 * Delete account
 *
 * @return Response
 */
public function deleteAccount(Request $request)
{

    // attempt to delete account
    try {

        $id = Auth::user();
        $user = User::findOrFail($id['id']);
        $user->delete();

        $items1 = MyFirstModel::where('user_id', $id['id'])->get();
        if (count($items1) > 0) {
          foreach ($items1 as $key => $item) {
            $item->delete();
          }
        }

        $items2 = MySecondModel::where('user_id', $id['id'])->get();
        if (count($items2) > 0) {
          foreach ($items2 as $key => $item) {
            $item->delete();
          }
        }

        // ... other models here.

        // everything went okay!
        return response()->json(['success' => true, 'message' => 'Your account has been deleted'], 200);

    } catch (Exception $e) {

        // catch the error
        return response()->json(['success' => false, 'message' => 'We was unable to delete your account at this time'], 422);

    }

}

Advertisement

Answer

You can hook into Model lifecycle events. In your example you want to delete related data when a Model is being deleted. So on your Model, do something like the following:

public function booted()
{
    static::deleted(function ($model) {
        $model->releationship()->delete();
    })
}

You can read more about model lifecycle events on the docs.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement