Laravel Auth : Multi Authentication System Using Guard

In this tutorial we are going to know how to create multi auth system in laravel?  In this tutorial we'll use guard to create this multi authentication system. Laravel default login system, laravel use web as a default guard

If you go to your loginController.php then you can see its use AuthenticatesUsers trait. So we will see that what is happening here. 

If you go this file which locate this following slug

vendor\laravel\framework\src\illuminate\Foundation\Auth\AuthenticatesUsers .php

 After going this file just go to bottom of this file and you will see many code of login system. But now we are going to create our own multi auth system in laravel 7.

Sometimes we need student login, teacher login and admin login etc. Such kind kind of situation we need multi auth in web application. Laravel provides awesome thing to do multi auth using guard.

So in this example tutorial i am going to show you how we can create multi auth system in our laravel 7 application.

laravel-multi-authentication-using-guard

Read also :  How to Send Email in Laravel 7 with Mailtrap

 

protected function guard() {
   return Auth::guard();
}

 

See guard method return a Auth::guard(). Now go config\auth.php then you can see defaults guard and this web

config\auth.php

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],

 

Now we also use guard to authenticate but it will be our custom guard. Now just one thing i wanna say before starting our multi authentication system. Visit this file which located in this slug 

vendor\laravel\framework\src\illuminate\Routing\Router.php

And go to the line number almost it will be near about 1120.Then you will find all the default route which is connected to laravel default authentication.

vendor\laravel\framework\src\illuminate\Routing\Router.php

 public function auth(){
   // Authentication Routes...
 $this->get('login', 'Auth\[email protected]')->name('login');
 $this->post('login', 'Auth\[email protected]');
 $this->post('logout', 'Auth\[email protected]')->name('logout');

   // Registration Routes...
 $this->get('register', 'Auth\[email protected]')->name('register');
 $this->post('register', 'Auth\[email protected]');

   // Password Reset Routes...
 $this->get('password/reset', 'Auth\[email protected]')->name('password.request');
 $this->post('password/email', 'Auth\[email protected]')->name('password.email');
 $this->get('password/reset/{token}', 'Auth\[email protected]')->name('password.reset');
 $this->post('password/reset', 'Auth\[email protected]');
}

 

And keep in mind one important thing is laravel use User.php model to authenticate user. So if you go to user model you will this following code.

app/User.php

namespace App\user;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable; //Looks use Authenticatable

class User extends Authenticatable // And extend Authenticatable class
{
    use Notifiable;
  
    protected $fillable = [
        'name', 'email', 'password', 'provider' , 'provider_id'
    ];
   
    protected $hidden = [
        'password', 'remember_token',
    ];
}

 

Look this model use Illuminate\Foundation\Auth\User as Authenticatable and extends Authenticatable class. Hope you will get all those point.

Now we are going to create our custom laravel multi authentication sytem using guardIt is very simple and it would be easily understandable. Hope you will understand.

 

Step 1: Create default auth

Doing it first run this below command.

php artisan make:auth

after running this command a auth folder is created in our resources\views\auth directory. 

 

Step 2:  Create our custom route

Now go to your routes\web.php and paste this following code. 

routes\web.php

Route::group(['namespace' => 'Admin'] , function(){

  /****Admin Login Route*****/
  Route::get('backend/login', 'Auth\[email protected]')->name('admin.login');
  Route::post('backend/login', 'Auth\[email protected]');
  Route::post('backend/logout', 'Auth\[email protected]')->name('logout');

});

 

Look avobe all those controller are grouped and located inside Admin\Auth folder. Hope you will get it. That mean copy Auth folder and paste it into Admin folder.

Finally slug will look like App\Http\Controllers\Admin\Auth . Hope you will understand. Now go to your Admin\Auth folder and change all those namespace like below.

 

namespace App\Http\Controllers\Admin\Auth;

Added this line avobe your all Auth Controller. 

Step 3: Create Migration

Run this below command to create our table. 

php artisan make:model Model\Admin\Admin -m

 

Now go to your migration folder and open our admins table file and paste this following code.

public function up() {
        Schema::create('admins', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->integer('user_role');
            $table->boolean('status')->nullable();
            $table->timestamps();
        });
}

Now run following command 

php artisan migrate

After running this command our migration will be completed.

Step 4:  Setup Guard

Now go to your config\auth.php file and do this which i have done in my auth.php file.

config\auth.php

return [

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],


    'guards' => [
        'web' => [ //Laravel default guard name
            'driver' => 'session', 
            'provider' => 'users', // Laravel authenticate table/model name
        ],
        
        'admin' => [  //Our Custom guard name "admin"
            'driver' => 'session',  
            'provider' => 'admins',  // Our authenticate table/model name
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],

        
    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class, //Laravel guard model slug
        ],

        'admins' => [  
            'driver' => 'eloquent',  //Our custom eloquent
            'model' => App\Model\Admin\Admin::class, //Our custom guard model slug
        ],
    ],

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],

        'admins' => [  // And here also
            'provider' => 'admins',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

];

Hope you will understand what i have done in auth.php file.

Step 5: Setup our Admin model

Now time to setup our Admin.php modelFirst i told you that Laravel User model extend Authenticable to authenticate users. Now we will also extends this class. So just pase this below code to your Admin.php model.

app/Model/Admin/Admin.php

namespace App\Model\admin;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Admin extends Authenticatable //Look this model extends Authenticatable not extends Model
{
    use Notifiable;
}

Step 6: Customize our LoginController

Now go you login controller which is located inside App\Http\Controllers\Admin\Auth\LoginController.php and paste this following code.

App\Http\Controllers\Admin\Auth\LoginController.php

namespace App\Http\Controllers\Admin\Auth;

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

class LoginController extends Controller
{  

    use AuthenticatesUsers;
    
    protected $redirectTo = '/backend'; //Redirect after authenticate

    public function __construct()
    {
        $this->middleware('guest:admin')->except('logout'); //Notice this middleware
    }

    public function showLoginForm() //Go web.php then you will find this route
    {
        return view('admin.login');
    }
    
    public function login(Request $request) //Go web.php then you will find this route
    {
         $this->validateLogin($request);

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        return $this->sendFailedLoginResponse($request);
       
    }

     public function logout(Request $request)
    {
        $this->guard('admin')->logout();

        $request->session()->invalidate();

        return redirect('/login');
    }

     protected function guard() // And now finally this is our custom guard name
    {
        return Auth::guard('admin');
    }
}

 

All those above method you will find AuthenticatesUsers trait which i showed you before. All those coding part is almost done. Now time to setup our blade file.

Step 7:  Setup our login button

 

For making login button just add this action to your login form.

action="{{ route('admin.login') }}"

And for Sign out button just add this below code.

 

Now enter this slug http://127.0.0.1:8000/backend/login  . After visiting this slug you can see you login page and now go to your database and insert Username Email and Password manually then hit login . Hope it will work. 

Step 8: Fix Bugs

Have you notice, without login you can access  http://127.0.0.1:8000/backend/  this slug. Also after login you can access login page. This is not acceptable .

So for solving this issue go to followingurl and paste this following code in the handle method.

App\Http\Middleware\RedirectIfAuthenticated.php

public function handle($request, Closure $next, $guard = null) {   
        
   switch ($guard) {
     case 'admin':
             if (Auth::guard($guard)->check()) {
             return redirect('/backend');
          }
             break;

     default:
             if (Auth::guard($guard)->check()) {
              return redirect('/');
             }
             break;
          }
     
  return $next($request);
}

 

Look what i did here ? if a user is logged in then redirect him into backend and if not logged in then redirect him into home page or our root domain slug. Hope you will understand.

If you face any problem or error then share you error with me. Of course i will try to help you. If you know the better approach to do Laravel multi authentication system then you can share with me also. 

 

Note: Check active or not

If you want only active user can logged in then you have to just add some code to your credentials method. just check

 protected function credentials(Request $request){  
   if (Auth::attempt(['email' => $email, 'password' => $password, 'active' => 1])) {
     return $request->only($this->username(), 'password');
  }       
}

Hope it will work. Hope this laravel multi authentication tutorial will help you.

A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using JavaScript, Laravel & Wordpress specifically. Facebook Github Website