Search code examples
mysqllaraveleloquentrelationshipdingo-api

Eloquent delete and MySQL foreign key cascade


I have these tables in MySQL database:

users['id', 'name'],

roles['id', 'title'] and

user_role ['user_id', 'role_id'] where both are foreign keys, CASCADE.


When it catches an exception the user remains in the table as wanted, while the row from the relation table is deleted.

try{
    $user->delete();
}
catch (\Exception $e){
    throw new \Dingo\Api\Exception\DeleteResourceFailedException('Error.');
}

Is this eloquent's mistake?


Now, I figured out a way to fix this but I'm not sure that it's the best practise. Is there a better way to do it?

try{
    $roleId = $user->roles[0]->id;
    $user->delete();
}
catch (\Exception $e){
    $user->roles()->attach($roleId);
    throw new \Dingo\Api\Exception\DeleteResourceFailedException('Error.');
}

Solution

  • If i understood your question, transactions are what you need.

    Database Transactions

    DB::transaction(function () {
        $user->delete();
    });
    

    and in case you face a deadlock use this one

     DB::transaction(function () {
        $user->delete();
    },5);