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.

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

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

 '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

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', 'HomeController@superHome')->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

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')
Dashboard
You are normal user.
@endsection

resources/views/superHome.blade.php

@extends('layouts.app')
   
@section('content')
Dashboard - www.pakainfo.com
You are Super Admin.
@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

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

'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.

Leave a Comment