Laravel 6 multi auth tutorial and code example

Laravel 6 multi auth tutorial and code example


Are you looking for multiple authentication tutorial and code example for Laravel? Confused continuously seeking tutorial from different laravel article? No more looking forward to multi authentication for laravel framework.

In this tutorial, I'll show you clearly and give code example for how to make multi auth in Laravel 6 step by step natively without any third-party package. Following this tutorial, you can also make multi auth for Laravel 5.5, 5.6, 5.7 and 5.8.

Working Plan

For this tutorial, we'll make the authentication system for 2 user group normal user and admin. For the normal user, we use default auth scaffold and for admin, we have to make some stuff and changes.

Laravel 6 Multiple Authentication steps overview

  • Step 01: Install Laravel 6
  • Step 02: Install Laravel UI
  • Step 03: Database Configuration
  • Step 04: Migration
  • Step 05: Model Setup
  • Step 06: Setup the auth.php config
  • Step 07: Define routes
  • Step 08: Admin authentication controller
  • Step 09: Admin login form
  • Step 10: Handle unauthorized admin redirection

Step 01: Install Laravel 6

Install Laravel 6 with this command. You can do the exact same thing in Laravel >5.5 version also.

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

Step 02: Install Laravel UI

In Laravel 6 by default, make:auth the command is not available. You have to install a package laravel/ui to generate auth scaffold. Keep in mind this is required only if you are using Laravel 6 version otherwise you have to leave this step.

composer require laravel/ui --dev
php artisan ui bootstrap --auth

Step 03: Database Configuration

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=dbname
DB_USERNAME=root
DB_PASSWORD=

Step 04: Migration

Make a copy of the user migration file with the name of 2014_10_12_000000_create_admins_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateAdminsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('admins', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('admins');
    }
} 

save the file and run migration.

php artisan migrate

Step 05: Model Setup

Make an admin model. Here we have copied user model and did some modification.

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;


class Admin  extends Authenticatable
{
    use Notifiable;

    protected $guard = 'admin';

    protected $fillable = [
        'name', 'email', 'username', 'password','email_verfied_at'
    ];

    protected $hidden = ['password'];


} 

In this admin model, we have set $guard = 'admin' which we'll configure in auth.php config file later.

Step 06: Setup the auth.php config

Add new guard for admin in guards section.

'guards' => [
  ...
  ...
  'admin' => [
     'driver' => 'session',
     'provider' => 'admins',
  ]
];

Add a new provider in the provider's section for admin guard provider.

'providers' => [
  ...
  ...
  'admins' => [
     'driver' => 'eloquent',
     'model' => App\Admin::class,
  ]
];

Step 07: Define routes

Route::namespace('Admin')->name('admin.')->prefix('admin')->group(function () {
    Route::get('login', 'AdminAuthController@getLogin')->name('login');
    Route::post('login', 'AdminAuthController@postLogin');
})

Step 08: Admin authentication controller

Let's make a controller for admin authentication with a separate admin folder. So that our admin related controllers will be in the same namespace.

<?php

namespace App\Http\Controllers\Admin;

use App\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;

class AdminAuthController extends Controller
{
    use AuthenticatesUsers;

    protected $guardName = 'admin';
    protected $maxAttempts = 3;
    protected $decayMinutes = 2;

    protected $loginRoute;

    public function __construct()
    {
        $this->middleware('guest:admin')->except('postLogout');
        $this->loginRoute = route('admin.login');
    }

    public function getLogin()
    {
        return view('admin.login');
    }

    public function postLogout()
    {
        Auth::guard($this->guardName)->logout();
        Session::flush();
        return redirect()->guest($this->loginRoute);
    }

    public function postLogin(Request $request)
    {
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required|min:5'
        ]);

        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);
            $this->sendLockoutResponse($request);
        }

        $credential = [
            'email' => $request->input('email'),
            'password' => $request->input('password')
        ];

        
        if (Auth::guard($this->guardName)->attempt($credential)) {

            $request->session()->regenerate();
            $this->clearLoginAttempts($request);
            return redirect()->intended();

        } else {
            $this->incrementLoginAttempts($request);

            return redirect()->back()
                ->withInput()
                ->withErrors(["Incorrect user login details!"]);
        }
    }

} 

Step 09: Admin login form

Here I'm showing only login form with minimal design. You can change your required design. Create a login.blade.php file in resources/admin folder.

<form method="POST" action="" method="POST">
        @csrf
        <div class="form-group">
            <p>Email</p>
            <input class="form-control" name="email" type="email" required value="">
        </div>

        <div class="form-group">
            <p>Password</p>
            <input class="form-control" name="password" type="password" required>
        </div>
        <div class="form-group">
            <button class="btn btn-primary" type="submit">Login</button>
        </div>
</form>

Step 10: Handle unauthorized admin redirection

If anyone tries to access admin routes without login as an admin then by default it'll redirect to user login but our goal to redirect to our desired route for admin login route. For doing this we have to change the unauthenticated method in app/Exceptions/Handler.php

protected function unauthenticated($request, AuthenticationException $exception)
{
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        $guard = Arr::get($exception->guards(), 0);
        switch ($guard) {
            case 'admin':
                $login = 'admin/login';
                break;
            default:
                $login = 'login';
                break;
        }
        return redirect()->guest(url($login));
}

Our desired multiple authentication system is ready to use. We have use middleware to protect admin routes either in routes file or controller constructor according to our needs like below.

In routes

Route::middleware('auth:admin')->group(function(){
  //here all your admin routes

})

or by Controller constructor

public function __construct()
{
   $this->middleware('auth:admin');
}

 

Hope this step by step tutorial on Laravel multiple authentications will help you to make your desire multi auth in Laravel application. If you find this helpful please share with others.


Share on


sidebar ad


Related Post


Laravel Barcode generation tutorial

Laravel PDF generation tutorial

Laravel 7 Http facade

Laravel Validation Cheat Sheet

PEST - Make Laravel test easier

Laravel Google reCaptcha without package