samedi 26 décembre 2015

Delete a User with foreign key constraints

I'm working on a Laravel Application for managing case studies with a full admin dashboard that includes CRUD functionality for user accounts that can log into the system.

In short, a case study and a user have a one to many relationship (a user can have many case studies, a case study can only be authored by one user); a case study must always have a user that authored it. The problem I'm encountering is when I call the destroy method on my users controller to delete a user, it does not work because there are case studies in the DB that have that user associated with them and I run into a foreign key constraint violation.

I'm trying to figure out the best way to solve this problem. I was thinking I could create a user called "Deleted User" to assign case studies to when their author is deleted. This "Deleted User" could never be deleted or modified in the DB. You would also not be able to log into the system as "Deleted User".

I don't know if this would be considered a bad practice and I also think I may have an issue with scalability. For example, if a user has 5,000 case studies associated with them and that user is deleted, I suspect it would take a very long time to alter 5,000 rows in the DB to attach the "Deleted User" user.

I'm using Sentinel to manage different levels of user permissions as well, so when a user is deleted, I also detach that user from it's respective role in the role_users pivot table.

I don't know if it's at all helpful, but here's my destroy function on UsersController:

public function destroy($id)
{
    $user = User::findOrFail($id);
    $user->delete();

    $role = Sentinel::findById($id)->roles()->first();
    $role->users()->detach($id);

    Helpers::flash('The user has been successfully deleted.');
    return redirect(route('admin.users.index'));
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire