I build package for my projects and I create table roles and permissions and middleware.
I enable CRUD for roles and permissions and link some roles and permissions to middleware.
The question:
when the user (administrator) deletes all roles and permissions
after that any user cant access to admin control panel.
What is the best way to avoid such a situation?
Add proper foreign keys to your DB and make them RESTRICT. That means you can't delete a permission if a user is bound to it. (or a role if a permission is bound to it).
EDIT ADDED CODE: For example two tables - roles and permissions - migrations attached:
Schema::create('roles', function($table)
{
$table->increments('id');
$table->string('name');
});
Schema::create('persmissions', function($table)
{
$table->increments('id');
$table->usingnedInteger('role_id');
$table->string('name');
$table->foreign('role_id')
->references('id')->on('roles')
->onDelete('restrict');
});
If there is a role 'admin' with an id of 1 and a permission 'delete_user' with role_id = 1 it is not possible to delete the role with the id 1 - mysql wouldn't allow you to do that. So you abstracted the problem to the database layer. You only can delete the role if you first delete the permission.
You can do the same with the user. So if a user has a role_id of 1 you can't delete the role with the id 1 until no user with a role_id of 1 exists.