Hello Everyone! I was planning to make basic administration web app in my free time, which will have 3 user types: regular user, admin and superadmin. Can someone with more experience in laravel give me some tips for the best way to implement that? Should I make users, roles, roles_permissions as separate tables in db, or all of this could be solved using middleware?
If your roles are quite small in number - you might be better starting out by just having some flags on the user models like 'is_admin', 'is_superadmin'. You can always change over to 'full fat' roles & permissions later if you need.
But if you need more complicated roles & permissions from the start, maybe have a look at bouncer or spatie's package which will take care of a lot of it for you.
To keep things simple. if your users will just have one role, create a role_id column in the users table.
Then create a class with some constants to avoid using magic numbers.
namespace App\Enums;
class Roles {
const USER = 1;
const ADMIN = 2;
const SUPER = 3;
}
class User extends Model {
public function isUser() {
return $this->role_id == Roles::USER
}
public function isAdmin() {
return $this->role_id == Roles::ADMIN
}
}
@ivan1996 Have a simple role column in your users table. Then use policies to authorize actions, checking users’ roles in your policy actions:
class FooPolicy
{
public function edit(User $user, Foo $foo)
{
// Only admins and super admins can edit foo models
return in_array($user->role, ['admin', 'super_admin']);
}
}