Creating multi authentication in laravel PHP framework 2022

Creating multi authentication in laravel PHP framework 2022

In this post, you will learn laravel multi auth system.This multi authentication works well with any laravel version Laravel 8, Laravel 9

In this tutorials we would be creating our multi authentication using a very simple method called middleware, and we would be making use of a single table. follow along as we get started.

Step 1: Install Laravel 

After you have installed PHP and Composer, you may create a new Laravel project via the Composer create-project command. The current version of Laravel is 9, so all we need to get fresh Laravel 9 version application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project laravel/laravel example-app

Or, you may create new Laravel projects by globally installing the Laravel installer via Composer:

composer global require laravel/installer
 
laravel new example-app

After the project has been created, start Laravel's local development server using the Laravel's Artisan CLI serve command:

cd example-app
 
php artisan serve

Step 2: Database Configuration

In this step, we will make database configuration for example database name, username, password etc for our application. So let's open .env file and fill all details like as bellow:

.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)

Step 3: Update Migration and Model

We need to add new row "role_id" in users table. than we can run  the migration. 

database/migrations/000_create_users_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration

{

    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->string('role_id');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

Now we need to run migration.

so let's run bellow command:

php artisan migrate

Create model for role

 php artisan make:model Role -m

This command will create the model and the migration file for the role tabel

Then in your migration file for the roles table, add the following code

Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });

after this, we need to run the migration command again so that a]our roles table would be created.

Then afterwards, we would goto app > models > users  and create a relationship.

public function role()
{
return $this->belongsTo(App/Models/Role,'role_id');
}

And in the Role model

public function user()
{
return $this->belongsTo(App/Models/Users,'role_id');
}

Next we create a seed file to insert a dumy user in our database: we would run this in our terminal

php artisan make:seed UserSeeder
php artisan make:seed RoleSeeder

under the UserSeeder in the Database >seedeers > UserSeeder

//import this at the top use Illuminate\Support\Facades\DB;
public function run()
    {
        DB::table('users')->insert([
            'name' => 'Maye Jacob',
            'role_id' => '1',
            'email' => 'info@mayeconcept.com.ng',
            'password' => bcrypt('12345678'),
        ]);
        DB::table('users')->insert([
            'name' => 'Jayboss',
            'role_id' => '2',
            'email' => 'test@gmail.com',
            'password' => bcrypt('12345678'),
        ]);
    }

under the RoleSeeder in the Database >seedeers > RoleSeeder 

//import this at the top use Illuminate\Support\Facades\DB;
public function run()
    {
        DB::table('roles')->insert([
            'name' => 'Admin',
        ]);
        DB::table('roles')->insert([
            'name' => 'User',
        ]);
    }

under the DatabaseSeeder in the Database >seedeers > DatabaseSeeder

//remember to import the class for both role seeder and the userseeder
//put this under the run function
$this->call(RoleSeeder::class);
$this->call(UserSeeder::class);

we are now ready to seed our database by running the following command:

php artisan db:seed

Once this is done, we need to install the laravel authentication with:

composer require laravel/ui 
//then we would generate basic scaffolding and login and registration for bootstrap
php artisan ui bootstrap
php artisan ui bootstrap --auth
//or Generate basic scaffolding and login and registration for Vue
php artisan ui vue
php artisan ui vue --auth
//or Generate basic scaffolding and login and registration for react
php artisan ui react
php artisan ui react --auth
Install NPM dependencies

Run this following command to install node dependency and compile CSS and js files:

npm install && npm run dev

Next we setup middleware and controller:

in our web.php under routes we need to use this group route and middleware to protect the user and the admin route

use middleware and group and prefix
Route::group(['as' => 'admin.','prefix' => 'admin','namspace' => 'Admin','middleware' => ['auth','admin']],function(){
Route::get('dashboard',[DashboardController::class, 'index']->name('dashboard');
//all admin rout goes here
});
// to use this route name, it would be admin.dashboard or whatever name you provide because a prefix has been added to it and the path would be /admin/dashboard

Route::group(['as' => 'user.','prefix' => 'user','namspace' => 'User','middleware' => ['auth','user']],function(){
Route::get('dashboard',[HomeControllers::class, 'index']->name('dashboard');
all user route goes here
});

Note:

//make sure to create each controllers in the Admin and User directory of the controlers
php artisan make:controller Admin/DashboardControllers
php artisan make:controller User/HomeControllers
ensure to import the namespace in web.php

We would now create our middleware for User and the Admin

php artisan make:middleware AdminMiddleware
php artisan make:middleware UserMiddleware
for laravel 9 admin middleware should look like this
public function handle(Request $request, Closure $next)
   {
       // return $next($request);
       if(Auth::check() && Auth::user()->role_id ==1){
           return $next($request);
       }else{
           return redirect()->route('login');
       }
   }
for laravel 8 and lower versions, just remove the Request and you would be fine

then for the user middleware
public function handle(Request $request, Closure $next)
   {
       // return $next($request);
       if(Auth::check() && Auth::user()->role_id ==2){
           return $next($request);
       }else{
           return redirect()->route('login');
       }
   }

Then the next thing is to go to the kernal.php to register the two middlewares under the routeMiddleware array

'admin' =>AdminMiddleware::class,
'user' =>UserMiddleware::class,

Then we would go to the RedirectIfAuthenticated under the middleware

public function handle(Request $request, Closure $next, ...$guards)
   {
       // $guards = empty($guards) ? [null] : $guards;
       // foreach ($guards as $guard) {
           // if (Auth::guard($guard)->check()) {
           //     return redirect(RouteServiceProvider::HOME);
           // }
           
       // }
       if (Auth::guard($guards)->check() && Auth::user()->role_id ==1) {
           return redirect()->route('admin.dashboard');
       }else if(Auth::guard($guards)->check() && Auth::user()->role_id ==2){
           return redirect()->route('user.dashboard');
       }else{
           return $next($request);
       }
       // return $next($request);
      
   }

Go to controllers > auth > logincontroller then do the following

protected $redirectTo;
public function __construct()
   {
       if(Auth::check() && Auth::user()->role_id == 1)
       {
           $this->redirectTo = route('admin.dashboard');
       }else{
           $this->redirectTo = route('user.dashboard');
       }
       $this->middleware('guest')->except('logout');
   }

Make sure you define the index function under the created controllers

public function index()
   {
       return view('admin.dashboard');
   }

create that view file in resources > views > admin > dashboard.blade.php and also do likewise for the user resources > views > user> dashboard.blade.php

Test the authentication system

Now our Laravel 9 Authentication is ready to use. To check authentication is successfully installed or not. First Run the project.

php artisan serve

I hope you find this article helpful! if you have any troubles understanding this process, you can drop a comment, and you would get a response.

 

Enjoy this article ? drop a comment below and add your own contribution.

Maye Jacob

Jacob Olorunmaye

Verified Expert
Passionate Backend Developer | Expert in PHP, Laravel, JavaScript, and Golang 🚀 | Crafting seamless, scalable solutions for the digital era

Leave a Reply

Your email address will not be published. Required fields are marked *