Laravel 6 Multiple Authentication System Example Tutorial

Laravel multi (auth) authentication- Today we are going to show you, how to create multi auth system in laravel 6. Mulitple auth system means multiple users can login in one application.

Multiple authentication is very important in the large application of laravel. Authentication is the process of recognizing user credentials.

Laravel Multi Auth System

Contents

  • Download Laravel Setup
  • Setup Database Credentials
  • Setting up migration and model
  • Define Route
  • Create Methods in Controller
  • Create Blade View
  • Start Development Server
  • Conclusion

Download Laravel Setup

First We need a fresh Laravel application. Use the below command to download the laravel 6.x fresh setup on your system. We will keep the name of folder LaraMulti

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

Setup Database Crendentials

After successfully download laravel Application, Go to your project .env file and set up database credential and move next step :

  DB_CONNECTION=mysql 
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name here
DB_USERNAME=here database username here
DB_PASSWORD=here database password here

Now we will install laravel 6 UI in your project using the below command:

composer require laravel/ui

Second use the below command for creating controllers and views for authentication:

php artisan ui vue --auth

This command will create routes, controllers and views  files for Laravel Login Authentication and registration. It means provide a basic laravel login authentication and registration Complete system.

Then add route in the web.php route

Auth::routes();

By adding above function will enable login, register, forgot password etc routes

Setting up Models and Migrations

Create and set up the model and migration for Admin:

php artisan make:model Admin -m

To set up the model for Admin, go to app/Admin.php and update the code with the following:

/**
 * Remove 'use Illuminate\Database\Eloquent\Model;'
 */
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admin extends Authenticatable
{
    use Notifiable;
// The authentication guard for admin
    protected $guard = 'admin';
     /**
      * The attributes that are mass assignable.
      *
      * @var array
      */
    protected $fillable = [
        'email', 'password',
    ];
     /**
      * The attributes that should be hidden for arrays.
      *
      * @var array
      */
    protected $hidden = [
        'password', 'remember_token',
    ];
}
To set up the migration table for Admin, go to database/migration/***_create_admins_table.php and update the code with the following:
//
{
    Schema::create('admins', function (Blueprint $table) {
            $table->increments('id');
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
    });
 }
//

Next, Run below command to create table

php artisan migrate

Now we will setup admin guard. To do so open config/auth.php file add below array under guards array

'admin' => [
   'driver' => 'session',
   'provider' => 'admins'
]

Next, Add provider for admin like below

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

After changes our config/auth.php will look like this

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

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

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => 10800,

];

Next, We will create admin login controller.

php artisan make:controller Admin/Auth/LoginController

To set up a login controller, go to app/Http/Controllers/Auth/AdminLoginController.php and update the code with the following:

<?php
namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

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 = '/admin/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest:admin')->except('logout');
    }
    protected function guard()
    {
        return \Auth::guard('admin');
    }
    /**
     * Show the application's login form.
     *
     * @return \Illuminate\Http\Response
     */
    public function showLoginForm()
    {
        return view('admin.auth.login');
    }

}

Set up the Login View for Admin

To create and set up the login view for Admin, go to resources/views/auth/ and create new folder called admin then create a new file login.blade.php. Copy the code in resources/views/auth/login.blade.php and paste in the new file. Now update the new file with the following:

// 
<div class="card-header">{{ __('Admin Login') }}</div>
<div class="card-body">
  <form method="POST" action="{{ route('admin.login') }}">
//

Set up the Home View for Admin

To create and set up the home view for Admin, go to resources/views/admin and create a new file home.blade.php. Copy the code from resources/views/home.blade.php and paste in the new file.

Set up Routes for Admin

To set up the web routes for your application, go to routes/web.php and update the code with the following:

Route::namespace('Admin')->prefix('admin')->as('admin.')->group(function() {
   Auth::routes(['register' => false]);
   Route::get('/home', '[email protected]')->name('home');
});

Set up Middleware for Redirection

To set up the middleware for redirection after authentication, go to app/Http/Middleware/RedirectIfAuthenticated.php and update the code with the following:

public function handle($request, Closure $next, $guard = null)
    {

        if (Auth::guard($guard)->check()) {
            if($guard === 'admin') {
                return redirect('/admin/home');    
            }
            return redirect('/home');
        }

        return $next($request);
    }

Congratulations!

You have successfully configure multiple authentication system.

Recommended Posts

Laravel Image Upload

One Comment

  1. contractorTef said:

    General professional New York

    The role of General building New York is actually to transmit to the client the entire location as a whole, and also not such as separately carried out job. Of specific relevance is actually the duty of the basic contractor during the course of the large-scale building and construction of apartment house of domestic kind, commercial facilities, commercial locations.

    kitchen remodeling ny;
    Industrial structures.

    Today, the list of building and construction services includes several company interior design. An entrepreneur as well as a consumer can devote a considerable amount of time-solving on all organizational problems. A even more rational service is actually to leave this duty to General building NY.

    November 24, 2020
    Reply

Leave a Reply

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