Skip to main content

Multiple Authentication System Using Guards in Laravel

Guards:

A guard is a way of supplying the logic that is used to identify authenticated users. Laravel provides different guards like sessions and tokens. The session guard maintains the state of the user in each request by cookies, and on the other hand, the token guard authenticates the user by checking a valid token in every request.

Providers:

Basically, the  provider is responsible for retrieving the information from the back-end storage. If the guard requires that the user must be validated against the back-end storage, then the implementation of retrieving the user goes into the authentication provider. Laravel ships with two default authentication providers like Database and Eloquent. The database authentication provider deals with the straightforward retrieval of the user credentials from the back-end storage, while Eloquent provides an abstraction layer that does the needful.

Robust and scalable PHP applications to enhance your web presence.

Process to set up Laravel auth:

  1. Create blank database and link it to Application. 
  2. Run bellow Command in Command Prompt
php artisan make:auth

and

php artisan migrate

This will scaffold the entire authentication system.

  1. Create the admin model and migration (You can create multiple model and migration).
php artisan make:model Models/Admins -m

This will create a migration file from the admins model.

Copy & Paste the bellow code in /app/Models/Admins.php

<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;

class Admins extends Authenticatable
{
    
    protected $guard = 'admin';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'firstname', 'midname', 'lastname', 'email', 'address', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

And also Copy & Paste bellow hilighted code in Admins Migration file (Path: database\migrations\_create_admins_table.php)

<?php

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

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

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

And run “php artisan migrate” command.

  1. In the config/auth.php file, set up the custom guard and provider for admins.
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
    
    'admin' => [
        'driver' => 'session',
        'provider' => 'admins',
    ],
    'admin-api' => [
        'driver' => 'token',
        'provider' => 'admins',
    ],
],

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
    
    'admins' => [
        'driver' => 'eloquent',
        'model' => App\Models\Admin::class,
    ],

   
],

  1. Create the AdminLoginController

php artisan make:controller Auth/AdminLoginController

This command will create a AdminLoginController file and then copy & paste the bellow code.

 

<?php

    namespace App\Http\Controllers\Auth;

    use Illuminate\Http\Request;
    use App\Http\Controllers\Controller;
    use Auth;
    use Route;

    class AdminLoginController extends Controller
    {
       
        public function __construct()
        {
          $this->middleware('guest:admin', ['except' => ['logout']]);
        }
        
        public function showLoginForm()
        {
          return view('auth.admin_login');
        }
        
        public function login(Request $request)
        {
          // Validate the form data
          $this->validate($request, [
            'email'   => 'required|email',
            'password' => 'required|min:6'
          ]);
          
          // Attempt to log the user in
          if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
            // if successful, then redirect to their intended location
            return redirect()->intended(route('admin.dashboard'));
          } 
          // if unsuccessful, then redirect back to the login with the form data
          return redirect()->back()->withInput($request->only('email', 'remember'));
        }
        
        public function logout()
        {
            Auth::guard('admin')->logout();
            return redirect('/admin');
        }
    }
  1. Create the AdminController

php artisan make:controller AdminController

This command will create a AdminController file and then copy & paste the bellow code.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AdminController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:admin');
    }
    /**
     * show dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('admin');
    }
}
  1. Create Admin Login Page

Copy & Paste bellow code for creating admin login page

@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">{{ __('Admin Login') }}</div>

                    <div class="card-body">
                        <form method="POST" action="{{ route('admin.login.submit') }}">
                            @csrf

                            <div class="form-group row">
                                <label for="email" class="col-sm-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>

                                <div class="col-md-6">
                                    <input id="email" type="email" class="form-control{{ $errors->has('email') ? ' is-invalid' : '' }}" name="email" value="{{ old('email') }}" required autofocus>

                                    @if ($errors->has('email'))
                                        <span class="invalid-feedback">
                                            <strong>{{ $errors->first('email') }}</strong>
                                        </span>
                                    @endif
                                </div>
                            </div>

                            <div class="form-group row">
                                <label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>

                                <div class="col-md-6">
                                    <input id="password" type="password" class="form-control{{ $errors->has('password') ? ' is-invalid' : '' }}" name="password" required>

                                    @if ($errors->has('password'))
                                        <span class="invalid-feedback">
                                            <strong>{{ $errors->first('password') }}</strong>
                                        </span>
                                    @endif
                                </div>
                            </div>

                            <div class="form-group row">
                                <div class="col-md-6 offset-md-4">
                                    <div class="checkbox">
                                        <label>
                                            <input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> {{ __('Remember Me') }}
                                        </label>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group row mb-0">
                                <div class="col-md-8 offset-md-4">
                                    <button type="submit" class="btn btn-primary">
                                        {{ __('Login') }}
                                    </button>

                                    <a class="btn btn-link" href="{{ route('password.request') }}">
                                        {{ __('Forgot Your Password?') }}
                                    </a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    @endsection
  1. Copy & Paste bellow code in Route file (Path: routes\web.php)
    
Route::prefix('admin')->group(function() {
   		Route::get('/login',
   		'Auth\AdminLoginController@showLoginForm')->name('admin.login');
   		Route::post('/login', 'Auth\AdminLoginController@login')->name('admin.login.submit');
   		Route::get('logout/', 'Auth\AdminLoginController@logout')->name('admin.logout');
    		Route::get('/', 'AdminController@index')->name('admin.dashboard');
  	}); 

Admin Login URL: http://localhost/admin/login

User Login URL: http://localhost/login

 

 

Satyajit Dey

Satyajit Dey

Satyaijt Dey is working with Trigent Software for more than a year as a Senior Software Engineer. He has strong experience in AWS, Laravel , Zend and Codeigniter frameworks in PHP. He has five years of experience in PHP domain.