I would say that it depends, if you only have two roles, then it's fine to just add an is_admin column to the users table. If you feel that it's a bit too close as you put it, just create a table called admin_users and do a foreign key with the id of the user (user_id).
Is this Auth pattern safe?
So I'm currently building an ecommerce site for PC hardware, and I need to have both an User and an Admin portal. The users are the customers of the site while the admins have their own UI where they update stock, pricing and respond to customer support requests. So far so good. So I was wondering how I would split the auth logic and my first idea was with a role column in the users table but that felt a bit too close to the user logic so instead GPT suggested I add an Auth Guard named admins and a separate table.
So here's what I did:
- Add the admins provider in config/auth.php
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', App\Models\User::class),
],
'admins'=> [
'driver' => 'eloquent',
'model' => App\Models\Admin::class
],
],
- Make an admin guard:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
And then I was getting error because my Admin model was just extending Models, and I had to change it to :
class Admin extends Authenticatable .
And finally I made separate Admin Controller for login etc.
Is this following best practices? From my testing it seems to work fine but I don't know if guards were meant to be used that way.
edit: Forgot to mention how the login logic executes: in AdminController:
public function login(Request $request)
{
$credentials = $request->validate([
'username' => 'required|string',
'password' => 'required|string',
]);
if (Auth::guard('admin')->attempt($credentials)) {
$request->session()->regenerate();
return redirect()->intended('/');
}
return back()->withErrors([
'username' => 'The provided credentials do not match our records.',
]);
}
So I use the Auth::guard('admin) command which seems to work fine.
Please or to participate in this conversation.