In this tutorial you will learn about the Laravel 8 Multi Auth (Authentication) Tutorial and its application with practical example.
In this Laravel 8 Multi Auth (Authentication) Tutorial I’ll show you how to create multi auth login in laravel. In this tutorial you will learn to create multi auth login system using middleware in laravel 8. In this article I’ll share example of Multiple authentication system multiple users can log in in one application according to their roles.
- Laravel 8 Multi Auth (Authentication) Tutorial
- Step 1: Install Laravel 8
- Step 2: Database Configuration
- Step 3: Update Migration and Model
- Step 4: Create Auth using scaffold
- Step 5: Create IsAdmin Middleware
- Step 6: Create Route
- Step 7: Add Method on Controller
- Step 8: Create Blade file
- Step 9: Update on LoginController
- Step 10: Create Seeder
- Run the seeder
When we want create separate user login or separate user/admin panel for users with different privileges or access rights in same application. With multi auth system we can allow different user to access different panel in application. In this example we will create a middleware for checking the user’s role. It is an admin or normal user. We will create middleware name admin and configuration in the kernal.php file and also in the route file.
Laravel 8 Multi Auth (Authentication) Tutorial
In this step by step tutorial you will learn about Multi Auth login in laravel. I will also demonstrate you to create laravel multi auth login using custom middleware. Please follow the instruction given below:
Step 1: Install Laravel 8
First of all we need to create a fresh laravel project, download and install Laravel 8 using the below command
1 |
composer create-project --prefer-dist laravel/laravel blog |
Step 2: Database Configuration
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
1 2 3 4 5 6 |
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
Now we will add new column “is_admin” in users table and model.
database/migrations/000_create_users_table.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email'); $table->timestamp('email_verified_at')->nullable(); $table->boolean('is_admin')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } } |
app/Models/User.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<?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; class User extends Authenticatable { use HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', 'is_admin' ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; } |
Now, run following command to migrate database schema.
1 |
php artisan migrate |
Step 4: Create Auth using scaffold
Now, we will generate laravel auth scaffold to create login, register and dashboard.
Laravel 8 UI Package
1 |
composer require laravel/ui |
Generate auth
1 2 3 4 5 |
php artisan ui bootstrap --auth npm install npm run dev |
Step 5: Create IsAdmin Middleware
1 |
php artisan make:middleware IsAdmin |
app/Http/middleware/IsAdmin.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php namespace App\Http\Middleware; use Closure; class IsAdmin { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if(auth()->user()->is_admin == 1){ return $next($request); } return redirect(‘home’)->with(‘error’,"You don't have admin access."); } } |
app/Http/Kernel.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
.... 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, 'is_admin' => \App\Http\Middleware\IsAdmin::class, ]; .... |
Step 6: Create Route
After this, we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?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('admin/home', [HomeController::class, 'adminHome'])->name('admin.home')->middleware('is_admin'); |
Step 7: Add Method on Controller
Now add adminHome() method for admin route in HomeController.
app/Http/Controllers/HomeController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<?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'); } } |
Step 8: Create Blade file
In this step we will create a new blade file for admin and update for user’s blade file as well.
resources/views/home.blade.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@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 normal user. </div> </div> </div> </div> </div> @endsection |
resources/views/adminHome.blade.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@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 Admin. </div> </div> </div> </div> </div> @endsection |
Step 9: Update on LoginController
Now, we will change the LoginController so at the time login we redirect user according to user role. Normal user redirect to home route and for admin user redirect to admin route.app/Http/Controllers/Auth/LoginController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; 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 = '/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()->is_admin == 1) { return redirect()->route('admin.home'); }else{ return redirect()->route('home'); } }else{ return redirect()->route('login') ->with('error','Email-Address And Password Are Wrong.'); } } } |
Step 10: Create Seeder
1 |
php artisan make:seeder CreateUsersSeeder |
database/seeds/CreateUsersSeeder.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?php use Illuminate\Database\Seeder; use App\Models\User; class CreateUsersSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $user = [ [ 'name'=>'Admin', 'email'=>'admin@w3adda.com', 'is_admin'=>'1', 'password'=> bcrypt('123456'), ], [ 'name'=>'User', 'email'=>'user@w3adda.com', 'is_admin'=>'0', 'password'=> bcrypt('123456'), ], ]; foreach ($user as $key => $value) { User::create($value); } } } |
Run the seeder
1 |
php artisan db:seed --class=CreateUsersSeeder |
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |