mercredi 27 septembre 2017

Laravel delete method deleting all rows

I have an if statement that checks a request that contains an array of 'services' that are assigned to a user and then removes / adds them if they have a 'checked' value.

The issue I am currently having is that even when specifying a row using ->first and specific where values, it is deleting all of the rows in the database.

// Loop through all the services
foreach ($request->services as $key => $value) {
    $serviceRecord = ServiceUser::where('user_id', $userId)->where('id', $value['id'])->first();

    // The service is checked and it doesn't currently exist in the pivot table (not assigned to user)
    if ($value['checked'] && !$serviceRecord) {
        // Create an array of new values to be inserted

    // The service is not checked and does exist in the user_service table (currently assigned, wanting to be removed)
    } elseif (!$value['checked'] && $serviceRecord) {
        $serviceId = $serviceRecord->id;
        // $activeBookingsWithService is a count to see if the service can be deleted

        if (!count($activeBookingsWithService)) {
            $serviceRecord->delete();
        }
    }
}

This is a slightly stripped down version of the if statement. When trying to debug I can confirm:

  • $request->services only contains one item
  • $userId is the correct value
  • $serviceRecord only returns 1 value that is correct

Is there anything obvious that might explain why all rows are being deleted? I have also swapped out the deletion part and updated the row values instead which also updates all the records in the database.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire