Laravel 9 Multiple Authentication Using Middleware

WebSolutionStuff | Apr-13-2022 | Categories : Laravel

In this article, we will see laravel 9 multiple authentications using middleware. Using middleware we authenticate the user. laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to your application's login screen.

So, let's see multiple authentication in laravel 9, laravel 9 multi auth using middleware, multi auth in laravel 9, laravel 9 multiple authentication using guard, laravel 9 multi auth.

Laravel 9 multi auth, create a middleware for checking the user. It is a super admin or user and manager. And create middleware and configure it in the kernal.php file.

In this example, we will add the three types of users:

1. User

2. Manager

3. Super Admin

When we log in as a user then it will redirect on user routes. If you log in as super admin then it will redirect on super admin routes.

Step 1: Install Laravel 9

In this step, we will create laravel 9 application using the below command and this is optional to create an application.

composer create-project laravel/laravel laravel-9-multi-auth

 

 

Step 2: Database Configuration

Now, we will configure a database in the .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_9_multi_auth
DB_USERNAME=root
DB_PASSWORD=

 

Step 3: Update Migration and Model

In this step, we will add the "type" column in the user's table and model.

database/migrations/create_users_table.php

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->tinyInteger('type')->default(0); /* Users: 0=>User, 1=>Super Admin, 2=>Manager */
            $table->rememberToken();
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
};

Now, run the migration using the below command.

php artisan migrate

 

 

After that, we will update the user model.

app/Models/User.php

<?php
  
namespace App\Models;
  
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\Casts\Attribute;
  
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
      
    protected $fillable = [
        'name',
        'email',
        'password',
        'type'
    ];
  
    protected $hidden = [
        'password',
        'remember_token',
    ];
  
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
     
    protected function type(): Attribute
    {
        return new Attribute(
            get: fn ($value) =>  ["user", "super-admin", "manager"][$value],
        );
    }
}

 

Step 4: Create Auth using scaffold

In this step, we will create authentication using the scaffold to create a login, register, and dashboard.

Laravel UI Package:

composer require laravel/ui

Create Auth:

php artisan ui bootstrap --auth
npm install & npm run dev

 

 

Step 5: Create MultiAuthUser Middleware

Now, we will create MultiAuthUser middleware that will restrict users to access other pages.

php artisan make:middleware MultiAuthUser

app/Http/middleware/MultiAuthUser.php

<?php
  
namespace App\Http\Middleware;
  
use Closure;
use Illuminate\Http\Request;
  
class MultiUserAuth
{  
    public function handle(Request $request, Closure $next, $userType)
    {
        if(auth()->user()->type == $userType){
            return $next($request);
        }
          
        return response()->json(['You do not have permission to access for this page.']);
        /* return response()->view('errors.check-permission'); */
    }
}

app/Http/Kernel.php

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    'user-access' => \App\Http\Middleware\MultiAuthUser::class,
];

 

Step 6: Create Routes

In this step, we will create a route with middleware and user types like manager and super-admin.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;  
use App\Http\Controllers\HomeController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('/', function () {
    return view('welcome');
});
  
Auth::routes();
  

// Users Routes

Route::middleware(['auth', 'user-access:user'])->group(function () {
  
    Route::get('/dashboard', [HomeController::class, 'index'])->name('dashboard');
});

// Manager Routes

Route::middleware(['auth', 'user-access:manager'])->group(function () {
  
    Route::get('/manager/dashboard', [HomeController::class, 'managerDashboard'])->name('manager.dashboard');
});  

// Super Admin Routes

Route::middleware(['auth', 'user-access:super-admin'])->group(function () {
  
    Route::get('/super-admin/dashboard', [HomeController::class, 'superAdminDashboard'])->name('super.admin.dashboard');
});

 

 

Step 7: Update Controller

Now, we will methods in the HomeController.php file.

app/Http/Controllers/HomeController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class HomeController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        return view('home');
    }

    public function managerDashboard()
    {
        return view('manager_dashboard');
    }

    public function superAdminDashboard()
    {
        return view('super_admin_dashboard');
    }
}

 

Step 8: Create a Blade file

In this step, we will create a blade file for the manager and super-admin.

resources/views/home.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Dashboard') }}</div>

                <div class="card-body">
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif
                     You are login as a user role.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

resources/views/manager_dashboard.blade.php

@extends('layouts.app')
@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Dashboard') }}</div> 
                <div class="card-body">
                    You are login as a manager role.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

 

 

resources/views/super_admin_dashboard.blade.php

@extends('layouts.app')
  
@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">{{ __('Dashboard') }}</div>
  
                <div class="card-body">
                     You are login as a super admin role
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

 

Step 9: Update LoginController

In this step, we will some changes to the LoginController.

app/Http/Controllers/Auth/LoginController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;

class LoginController extends Controller
{

    use AuthenticatesUsers;

    protected $redirectTo = RouteServiceProvider::HOME;

    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function login(Request $request)
    {   
        $input = $request->all();
     
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required',
        ]);
     
        if(auth()->attempt(array('email' => $input['email'], 'password' => $input['password'])))
        {
            if (auth()->user()->type == 'super-admin') {
                return redirect()->route('super.admin.dashboard');
            }else if (auth()->user()->type == 'manager') {
                return redirect()->route('manager.dashboard');
            }else{
                return redirect()->route('dashboard');
            }
        }else{
            return redirect()->route('login')
                ->with('error','Email-Address And Password Are Wrong.');
        }
          
    }
}

 

 

Step 10: Create Seeder

Now, we will create a seeder for the super admin and user.

php artisan make:seeder CreateUsersSeeder
<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\User;

class CreateUsersSeeder extends Seeder
{
    public function run()
    {
        $users = [
            [
               'name'=>'User',
               'email'=>'[email protected]',
               'type'=>0,
               'password'=> bcrypt('123456'),
            ],
            [
               'name'=>'Super Admin',
               'email'=>'[email protected]',
               'type'=>1,
               'password'=> bcrypt('123456'),
            ],
            [
               'name'=>'Manager',
               'email'=>'[email protected]',
               'type'=> 2,
               'password'=> bcrypt('123456'),
            ],
        ];
    
        foreach ($users as $key => $user) {
            User::create($user);
        }
    }
}

Now, run seeder using the below command:

php artisan db:seed --class=CreateUsersSeeder

After that, run the laravel application.

php artisan serve

Now, open the browser and add the given URL, and check created role using the email and password.

http://localhost:8000/login

 


You might also like :



Recommended Post


Featured Post






Follow us
facebooklogo github instagram twitter