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

21 Comments

  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
  2. mikaeel said:

    Hello, my name is Mikaeel Rigby!

    I`m a professional writer and I`m going to change your lifes onсe and for all
    Writing has been my passion since early childhood and now I can`t imagine my life without it.
    Most of my poems were sold throughout Canada, USA, China and even India. Also I`m working with services that help people to save their time.
    People ask me “Please, Mikaeel Rigby, I need your professional help” and I always accept the request, `cause I know, that only I can save their time!

    Professional Writer – Mikaeel – http://www.salemmonthly.comCorps

    December 16, 2020
    Reply
  3. nannie said:

    Hi guys, my name is Nannie Morris!

    I`m a professional writer and I`m going to change your lifes onсe and for all
    Writing has been my passion since early childhood and now I cannot imagine my life without it.
    Most of my books were sold throughout Canada, USA, China and even Australia. Also I`m working with services that help people to save their nerves.
    People ask me “Mr, Nannie, I need your professional help” and I always accept the request, `cause I know, that only I can solve all their problems!

    Professional Academic Writer – Nannie – elearninag.com Company

    December 18, 2020
    Reply
  4. kyran said:

    Hi and welcome to my website . I’m Kyran Mckinney.
    I have always dreamed of being a writer but never dreamed I’d make a career of it. In college, though, I assisted a fellow student who needed help. She could not stop complimenting me . Word got around and someone asked me for to help them just a week later. This time they would pay me for my work.
    During the summer, I started doing research paper writing for students at the local college. It helped me have fun that summer and even funded some of my college tuition. Today, I still offer my research paper writing to students.

    Professional Writer – Kyran – http://www.sarahhermans.com Band

    December 18, 2020
    Reply
  5. LedBrerly said:

    Viagra Effets Secondaires Eraveden cialis buy fradrady Cialis Como Tomar

    December 20, 2020
    Reply
  6. adnan said:

    Hi guys, my name is Adnan Underwood!

    I`m an academic writer and I`m going to change your lifes onсe and for all
    Writing has been my passion since early years and now I can`t imagine my life without it.
    Most of my books were sold throughout Canada, USA, Old England and even India. Also I`m working with services that help people to save their nerves.
    People ask me “Mr, Adnan, I need your professional help” and I always accept the request, `cause I know, that only I can save their time!

    Professional Academic Writer – Adnan – http://www.thecornelwesttheory.com Team

    December 22, 2020
    Reply
  7. JoshuaBeant said:

    Nuru Massage Erotic: exotic rubs

    Good day! Our employees those who make your daily life easier. Organization that operates more than five years.

    Special quality our tantric salon is not an enforced setting. We develop sites to create.
    Advise for you try whatever type massage techniques alreadytoday. Go to site and further clear details.

    December 29, 2020
    Reply
  8. ecoorini said:

    Стоимость септика для частного дома

    Обеспечиваем лучший завершающий результат
    Наша международная компания занимается не только лишь проектированием и сборкой, профессионалы дополнительно делают последующее сопровождение автономной канализации.
    Высококачественное сопровождение
    Автономная канализация цена под ключ-это сегодня наш профиль
    Автономная канализация в частном помещении – лучший выбор от компанииСборка септика – изрядно непростой процесс, предполагающий не только лишь строительство, но и дополнительно выбор нужной системы.

    January 1, 2021
    Reply
  9. Donte said:

    Have you ever thought about adding a little bit more than just your
    articles? I mean, what you say is valuable and everything.
    Nevertheless think about if you added some great graphics or videos to give your posts more, “pop”!
    Your content is excellent but with images and clips, this site could certainly be one of the best in its field.
    Wonderful blog!

    Stop by my blog post :: cheap flights

    January 31, 2021
    Reply
  10. Muoi said:

    Pretty! This has been a really wonderful article. Many thanks for supplying these details.

    Also visit my website: cheap flights

    February 1, 2021
    Reply
  11. Abraham said:

    I wanted to thank you for this good read!!
    I definitely loved every little bit of it.
    I have you bookmarked to look at new things you post…

    my blog post: cheap flights (http://tinyurl.com/y3eujkpl)

    February 2, 2021
    Reply
  12. Ted said:

    I need to to thank you for this fantastic read!!
    I absolutely loved every little bit of it. I’ve got you book
    marked to look at new things you post…

    Here is my website; cheap flights

    February 2, 2021
    Reply
  13. Cindy said:

    It’s really very complex in this active life to listen news on TV,
    thus I simply use world wide web for that reason, and take the hottest news.

    Also visit my web site – cheap flights (http://tinyurl.com/y35zw5en)

    February 3, 2021
    Reply
  14. reema said:

    Hello everyone, it’s Reema Bright here!
    I work as an academic writer and have created this content with the intent of changing your life for the better. I started honing my writing talent in high school. I learned that my fellow students needed writing help—and they were willing to pay for it. The money was enough to help pay my tuition for my first semester of college.
    Ever since high school, I have continued to work as an academic writer. I was hired by a writing company based in the United Kingdom. Since then, the essays that I have written have been sold around Europe and the United States.
    In my line of work, I have become used to hearing, “Reema Bright, can you help me meet my writing assignment deadline?” I know that I can save their time.

    Academic Writer – Reema Bright – http://www.glenrose.orgTeam

    February 4, 2021
    Reply
  15. Ismael said:

    If some one wishes expert view concerning blogging and site-building after that i recommend him/her
    to pay a visit this weblog, Keep up the fastidious work.

    my web-site; cheap flights [http://tinyurl.com/]

    February 12, 2021
    Reply
  16. Armando said:

    Most Famous Gothic Novels Of All Time Football Science Fair Projects For 8th Grade

    my homepage – pdf books

    February 17, 2021
    Reply
  17. Heriberto said:

    War And Peace Series Cast Bad Blood Book Page
    Count

    my site … pdf book

    February 17, 2021
    Reply
  18. adnan said:

    Hello everyone, it’s Adnan Underwood here!
    I work as an academic writer and have created this content with the intent of changing your life for the better. I started honing my writing talent in my school years. I learned that my fellow students needed writing help—and they were willing to pay for it. The money was enough to help pay my tuition for my remaining semesters of college.
    Ever since high school, I have continued to work as a professional writer. I was hired by a writing service based in the United Kingdom. Since then, the essays that I have created have been sold around Europe and the United States.
    In my line of work, I have become used to hearing, “Adnan, can you help me meet my writing assignment deadline?” I know that I can save their time.

    Professional Writer – Adnan – http://www.absinthenew.com Team

    February 24, 2021
    Reply
  19. camden said:

    I’m an academic writer who loves to bring smiles to people’s face.

    Writing is what I do for a living and I am so passionate about this. I have worked with several companies whose mission is to help people solve writing problems.
    I love traveling and have visited several places in the past few years.
    I’m happy to have written several books that have contributed positively to the lives of many. My works are available in several parts of the world. And I’m currently working with service providers that help people save time. Being a part of this team has open more opportunities for me to excel as a writer. I have worked with different people and met many clients as a writer.
    I can handle any kind of writing project and provide nothing but the best. People come to me all the time to ask if I can solve their assignment problems and I accept. I find pleasure in helping them to solve their problems as a professional.

    Professional Writer – Camden – http://www.screenwritersbootcamp.com Corp

    February 25, 2021
    Reply

Leave a Reply

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