This tutorial is focused on laravel 9 multi auth. I would like to show you laravel 9 multiple authentication. you'll learn multiple authentication in laravel 9. it's a simple example of laravel 9 multiple authentication using middleware. So, let's follow a few steps to create an example of laravel 9 multiple auth middleware.
I have written many tutorials about multi authentication in laravel. in this tutorial, we will create a multi auth very simple way using middleware with a single table. if you want to create multiple authentications using guard then you can follow this tutorial: Laravel multi auth example using Auth guard from scratch and if you want to create multiple authentications with laravel using role and middleware than you can follow this tuto: Laravel 5 - Simple user access control using Middleware
However, In this example, we will add the following three types of users as below:
1) User
2) Manager
3) Admin
When we log in as admin then it will redirect on admin routes, If you log in as manager then it will redirect on manager routes.
So, let's see follow simple steps:
Step 1: Install Laravel 9
This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:
In second step, we will make database configuration for example database name, username, password etc for our crud application of laravel 9. So let's open .env file and fill all details like as bellow:
.env
DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=here your database name(blog)DB_USERNAME=here database username(root)DB_PASSWORD=here database password(root)
Here, We will add following routes group where you can create new routes for users, admins and manager access. let's update code:
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(); /*--------------------------------------------------------------------------------------All Normal Users Routes List----------------------------------------------------------------------------------------*/Route::middleware(['auth', 'user-access:user'])->group(function () { Route::get('/home', [HomeController::class, 'index'])->name('home');}); /*--------------------------------------------------------------------------------------All Admin Routes List----------------------------------------------------------------------------------------*/Route::middleware(['auth', 'user-access:admin'])->group(function () { Route::get('/admin/home', [HomeController::class, 'adminHome'])->name('admin.home');}); /*--------------------------------------------------------------------------------------All Admin Routes List----------------------------------------------------------------------------------------*/Route::middleware(['auth', 'user-access:manager'])->group(function () { Route::get('/manager/home', [HomeController::class, 'managerHome'])->name('manager.home');});
Step 7: Update Controller
Here, we need add adminHome() and managerHome method for admin route in HomeController. so let's add like as bellow:
app/Http/Controllers/HomeController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class HomeController extends Controller{ /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function index() { return view('home'); } /** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function adminHome() { return view('adminHome'); } /** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function managerHome() { return view('managerHome'); }}
Step 8: Create Blade file
In this step, we need to create new blade file for admin and update for user blade file. so let's change it.
@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 a Admin User. </div> </div> </div> </div></div>@endsection
resources/views/managerHome.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 a Manager User. </div> </div> </div> </div></div>@endsection
Step 9: Update on LoginController
In this step, we will change on LoginController, when user will login than we redirect according to user access. if normal user than we will redirect to home route and if admin user than we redirect to admin route. so let's change.
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{ /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */ use AuthenticatesUsers; /** * Where to redirect users after login. * * @var string */ protected $redirectTo = RouteServiceProvider::HOME; /** * Create a new controller instance. * * @return void */ 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 == 'admin') { return redirect()->route('admin.home'); }else if (auth()->user()->type == 'manager') { return redirect()->route('manager.home'); }else{ return redirect()->route('home'); } }else{ return redirect()->route('login') ->with('error','Email-Address And Password Are Wrong.'); } }}
Step 10: Create Seeder
We will create seeder for create new admin and normal user. so let's create seeder using following command:
php artisan make:seeder CreateUsersSeeder
database/seeders/CreateUsersSeeder.php
<?php namespace Database\Seeders; use Illuminate\Database\Console\Seeds\WithoutModelEvents;use Illuminate\Database\Seeder;use App\Models\User; class CreateUsersSeeder extends Seeder{ /** * Run the database seeds. * * @return void */ public function run() { $users = [ [ 'name'=>'Admin User', 'email'=>'admin@itsolutionstuff.com', 'type'=>1, 'password'=> bcrypt('123456'), ], [ 'name'=>'Manager User', 'email'=>'manager@itsolutionstuff.com', 'type'=> 2, 'password'=> bcrypt('123456'), ], [ 'name'=>'User', 'email'=>'user@itsolutionstuff.com', 'type'=>0, 'password'=> bcrypt('123456'), ], ]; foreach ($users as $key => $user) { User::create($user); } }}
Now let's run seeder:
php artisan db:seed --class=CreateUsersSeeder
Run Laravel App:
All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:
php artisan serve
Now, Go to your web browser, type the given URL and view the app output: