laravel multi auth (Authentication) guards Example

In this laravel multi auth example, We would like to share with you how to create laravel 5/6/7 multiple authentication using middleware. we will create multi auth in laravel 5/6/7 using middleware. We will write step by step example of creating multiple authentication in laravel 5/6/7.

List of all Google Adsense, VueJS, AngularJS, PHP, Laravel Examples.

Laravel 7/6 Multi Auth (Authentication) Tutorial

I written many tutorials about multi authentication in laravel. in this example we will create multi auth login and logout very easy technique using middleware with single Database table. if you want to create multiple authentication using guard than you can bellow this example: Laravel multi auth example using Auth guard from step by step for Advanced Level and if you want to create multiple guards authentication with laravel using role and middleware than you can bellow this Free Tutorials and Source Code: Laravel 5/6/7 – Simple user permissions control using Middleware

Anyway Let’s start in this example, we will make very easy technique and you can easily use with your laravel 5/6/7 application. so let’s bellow like as step.

PHP Multiple Authentication using Laravel 5.7 Middleware
PHP Multiple Authentication using Laravel 5.7 Middleware

Prerequisites: Laravel Multiple Guards Authentication: Setup and Login

  1. Understanding of PHP (version >= 7.1.3).
  2. Understanding of Laravel Latest Versions
  3. Composer is installed & working on your computer (version >= 1.3.2).
  4. Laravel installer is installed & working on your computer.

Step 1: Create the application & Install Laravel 5/6/7

first of all we need to get fresh Laravel 5/6/7 version application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel laravel_multi_auth

Step 2: Create the database & Database Configuration

In second phase, we will make database configuration for example database name, username, password etc for our crud application of laravel 6. 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=laravel_multi_auth
DB_USERNAME=root
DB_PASSWORD=Tamilrokets

Step 3: Creating & Update Migration and Model

In this phase, we need to add new row “is_super” in users database table and model. than we need to run migration. so let’s change that on both file.
database/migrations/22548555_create_users_table.php

<?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->bigIncrements('id');
            $table->string('name');
            $table->string('email');
            $table->timestamp('email_verified_at')->nullable();
            $table->boolean('is_super')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Set up the models

app/User.php

<?php
   
namespace App;
   
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
   
class User extends Authenticatable
{
    use Notifiable;
   
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'is_super'
    ];
   
    /**
     * 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 we need to run migration.

so let’s run bellow command on Command Prompt:

php artisan migrate

Step 4: Create Auth using scaffold

Now, in this phase, we will make auth scaffold command to make signin, register as well as dashboard. therefor run/execute bellow commands in Command Prompt:
Laravel 6 UI Package

composer require laravel/ui 

Set up authentication pages

php artisan ui bootstrap --auth 

npm install

npm run dev

Step 5: Create IsSuper Middleware

In this phase, we need to make super middleware that will authorize only super permissions users to that routes. therefor let’s make super user with bellow phases.

php artisan make:middleware IsSuper

app/Http/middleware/IsSuper.php
<?php
  
namespace App\Http\Middleware;
  
use Closure;
   
class IsSuper
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(auth()->user()->is_super == 1){
            return $next($request);
        }
   
        return redirect(‘home’)->with(‘error’,"sorry, Dear You don't have any types of the super permissions.");
    }
}

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,
    'is_super' => \App\Http\Middleware\IsSuper::class,
];
....

Step 6: Set up the routes

Here, we need to add one more route for super user home page so let’s add that route in web.php file.
routes/web.php

Route::get('super/home', '[email protected]')->name('super.home')->middleware('is_super');

Step 7: Add Method on Controller

Here, we need add superHome() method for super 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 superHome()
    {
        return view('superHome');
    }
    
}

Step 8: Create Blade file

In this phase, we need to make new blade file for super and update for user blade file. so let’s change it.
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">
                    You are normal user.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

resources/views/superHome.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 - www.pakainfo.com</div>
                <div class="card-body">
                    You are Super Admin.
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Step 9: Update on LoginController

In this phase, we will change on LoginController, when user will login than we redirect according to user permissions. if normal user than we will redirect to home route and if super Admin user than we redirect to super Admin route. so let’s change.
app/Http/Controllers/Auth/LoginController.php

<?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_super == 1) {
                return redirect()->route('super.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 make seeder for make fresh super admin as well as normal user. therefor let’s make run seeder using bellow command on Command Prompt:

php artisan make:seeder CreateUsersSeeder

database/seeds/CreateUsersSeeder.php

<?php
  
use Illuminate\Database\Seeder;
use App\User;
   
class CreateUsersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $user = [
            [
               'name'=>'superAdmin',
               'email'=>'[email protected]',
                'is_super'=>'1',
               'password'=> bcrypt('982560'),
            ],
            [
               'name'=>'User',
               'email'=>'[email protected]',
                'is_super'=>'0',
               'password'=> bcrypt('982560'),
            ],
        ];
  
        foreach ($user as $key => $value) {
            User::create($value);
        }
    }
}

Run the application

Now let’s you can simply run seeder:
Ok, and the I am ready to run “laravel multi auth” simple application.
and last step to let’s run laravel app & Laravel Clear Cache Using Artisan Command (CLI) On Command Prompt:

php artisan db:seed --class=CreateUsersSeeder
php artisan serve

Super Admin User

Email: [email protected]
Password: 982560

Normal User
Email: [email protected]
Password: 982560

Conclusion

In this Example, we dived more Advance Details into Laravel 5/6/7 authentication. We defined USE MULTIPLE AUTHENTICATION GUARDS IN A LARAVEL APP to handle multiple Auth and permissions each Users each control. We also handle check Auth and redirection for authenticated user role and redirection for an unauthenticated each user valid Web pages.

If you followed this steps perfectly, you will be able to set up the base authentication for an Laravel Projects with different user classes (hopefully a use large scale multitenant Laravel Projects). Be that as it may, try increase what you have understand and share what you come up with our Tutorials.

The Complete full source code to the Laravel Projects in this article is available on Our Website.

Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about laravel multi auth.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


Related FAQ

Here are some more FAQ related to this Article:

  1.   Laravel Multiple Authentication Example
  2.   PHP Multiple Authentication using Laravel 5.7 Middleware
  3.   AJAX Pagination with Laravel 5.7 Example From Scratch
  4.   PHP Laravel 6 create Pagination Example - demo
  5.   PHP Strong Random Number and String Generator
  6.   Creating Dynamic Email Template in PHP
  7.   Ajax not working in laravel 5.6
  8.   Solution Fatal error: Call to undefined function base_url() in Codeigniter
  9.   PHP Codeigniter URL Routing Automatically
  10.   How to Convert date string to date PHP

Leave a Reply

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