562 views
asked in Laravel by
Laravel 10 Multiple Authentication Using Middleware

1 Answer

answered by

Laravel 10 Multiple Authentication Using Middleware


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

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

1. User

2. Admin

3. Super Admin

When we log in as an user then it will redirect to related user routes. If you log in as super admin and admin then it will redirect to super admin and admin routes respectively.

Step 1: Install Laravel 10

In this step, we will install the laravel 10 application using the below command.

composer create-project --prefer-dist laravel/laravel MultiAuthLaravel_10
cd MultiAuthLaravel_10

Open your project in any text editor like vscode, sublime, notepad++ etc.

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=MultiAuthLaravel_10
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=>Admin, 2=>Super Admin */

            $table->rememberToken();

            $table->timestamps();

        });

    }

  

    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        Schema::dropIfExists('users');

    }

}

At this juncture, execute the migration by using the following 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", "admin", "super-admin"][$value],

        );

    }

}

Step 4: Create Auth using scaffold

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(['Access to this page is restricted. Unauthorized access is prohibited.']);

    }

}


//app/Http/Kernel.php


protected $routeMiddleware = [

    ............

    '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 user, admin 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');

});


// admin Routes


Route::middleware(['auth', 'user-access:admin'])->group(function () {

  

    Route::get('/admin/dashboard', [HomeController::class, 'adminDashboard'])->name('admin.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 the Controller

Now, we will add 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 adminDashboard()

    {

        return view('admin_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 admin 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/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 admin 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 == 'admin') {

                return redirect()->route('admin.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'=>'user@chirags.in',

               'type'=>0,

               'password'=> Hash::make('12345678'),

            ],

            [

               'name'=>'admin',

               'email'=>'admin@chirags.in',

               'type'=> 1,

               'password'=> Hash::make('12345678'),

            ],

            [

               'name'=>'Super Admin',

               'email'=>'superadmin@chirags.in',

               'type'=>2,

               'password'=> Hash::make('12345678'),

            ],

        ];

    

        foreach ($users as $key => $user) {

            User::create($user);

        }

    }

}

Now, initiate the seeder by executing the following command:

php artisan db:seed --class=CreateUsersSeeder

Subsequently, launch the Laravel application.

php artisan serve

At this point, access your browser and navigate to the provided URL. Verify the assigned role by logging in with the specified email and password.

http://127.0.0.1:8000/login

Most popular tags

laravel postgresql laravel-10 replication ha postgresql mongodb laravel-11 mongodb database mongodb tutorial ubuntu 24.04 lts streaming-replication mysql database laravel postgresql backup laravel login register logout database mysql php laravel 11 - login with otp valid for 10 minutes. user and admin registration user and admin login multiauth technlogy asp.net asp.net c# mysql master slave replication centos linux laravel sql server schedule backup autobackup postgresql django python haproxy load balancer install self sign ssl laravel 11 gaurds zabbix 7 how to install graylog on ubuntu 24.04 lts | step-by-step asp.net core mvc .net mvc network upload c# ssl integration sql server on ubuntu 22.04 lts mssql server ms sql server sql server user access in postgres mysql password change cent os linux configure replica laravel 11 socialite login with google account google login kubernetes (k8s) install nginx load balancer install install and configure .net 8.0 in ubuntu 24.04 lts php in iis php with iis php tutorial chirags php tutorials chirags php tutorial chirags tutorial laravel 11 guards mongodb sharding metabase business analytics metabase postgresql 16 to postgresql 17 postgresql migration letsencrypt mongodb crud rocky linux laravel custom captcha laravel 11 captcha laravel captcha mongo dll php.ini debian 12 nginx apache nextcloud gitea in ubuntu git gitea npm error node js mysql ndb cluster mysql cluster ssl oracle login register logout in python debian windows shell batch file bat file time stamp date time shopping cart in laravel centos rhel swap memeory rhel 5.5
...