Multiple Auth Scope For Different Roles - Laravel 5.8
All it takes is to have a column that states user’s role, and a registered middleware to check role for authenticated user.
By this method, you can maintain the default auth setup and single login view for all users.
I will assume you already have laravel installed on your machine. You learn more here: Installing Laravel
After installing laravel, and creating a project, we can make auth and setup our middleware.
php artisan make:auth
Let’s edit our db table, assuming you are connected to MySQL database; in the create_users_table migration file, a field indicating role will be added.
This will help us track users based on their role.
You can have as many roles added, but we are going to look at admin role.
We are going to add role column to $guarded attribute in the users table to protect against mass assigning role.
The above shows the User class model, with role attribute guarded. Guarding the role attribute is optional since $fillable is already declared.
Let us take a look at the create_users_table migration file which was created when we ran php artisan make:auth.
To specify account role for each user, a column with default value which can be changed to give admin access will be added.
$table->enum('role', ['member', 'admin'])->default('member');
php artisan migrate:fresh
* Running this command will drop all tables and re-run migration.
Next is to create and register middleware which we will assign to the routes we intend to protect.
php artisan make:middleware Admin
We are going to make some changes which will help us to use this middleware to protect specific routes in our app.
A check to verify the following has been added:
- User has a valid session,
- If valid session exists, user must have admin role.
Before we can use our middle, we have to add it to our app Kernel.
Under $routeMiddleware array in Kerner.php file, the following can be added to register our middleware:
'admin' => \App\Http\Middleware\Admin::class
We can now create a controller that will handle the actions attached to every admin route and attach our midlleware to it. Another approach is to add the middleware directly to the routes.
Here, I will demonstrate how we can attach our middleware to a controller.
php artisan make:controller AdminController
Now we have a controller that will house all admin protected route methods.
Let us added the following lines of code to our controller:
public function __construct()
With this we can now protect specific routes and make accessible only to users with admin role.