Multiple Authentication Example in Laravel 5

Last Updated: June 21, 2018

To implement the multiple authentication in Laravel you can follow the following steps
1 Create model for Admin
2 Define your guard in config\auth.php
3 Create Route
4 Create View for registration and login
5

Redirect authenticated users
Password Reset

1 Create model Admin

     php artisan make:model Admin -m

This will create the migration file too
You can open the migration file which has the name end with create_admins_table and edit the file with 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->rememberToken();
            $table->timestamps();
        });
    }

Now you can run the migration command to create the admins table in the database

php artisan migrate

Then you have to add some code to Admin.php model. You can copy the code from User.php model

namespace App;

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

class Admin extends Authenticatable
{
    use Notifiable;

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

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

2 Define the Guard

  'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

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

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

    ],

I have defined guard name admin in this code
Now you need to create provider for the admin guard

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

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

    ],

I have defined the provider admins here

Now you have to tell to Admin model that I am going to use admin guard.
In Admin.php model file you can add the following line protected $guard='admin'

class Admin extends Authenticatable
{
    use Notifiable;

    protected $guard='admin'

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

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

3 Create Route

Now I am going to create route and add middle ware to route

I have created the group route to make it easy

Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function () {
	Route::get('/', 'AdminController@index')->name("admin.home");
	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('password/reset', 'Auth\AdminForgotPasswordController@showResetPasswordForm')->name('admin.password.request');
	Route::post('password/email', 'Auth\AdminForgotPasswordController@sendResetLinkEmail')->name('admin.password.email');
	Route::get('password/reset/{token}', 'Auth\AdminResetPasswordController@showResetForm')->name('admin.password.reset.token');
	Route::post('password/reset', 'Auth\AdminResetPasswordController@reset')->name('admin.password.reset.submit');

});

we have admin home page for logged admin users and we have login and logout pages too

Redirecting authenticated users

When you open the login page once you are authenticated it should redirect to some page
You can change the handle function of the in RedirectIfAuthenticated class App\Http\Middleware

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

        //return $next($request);
    }

Password Reset

In password reset process you have two views to deal with
1 email.blade.php
This view has the text field to enter the email address and a button to send password reset link to the given email

2 reset.blade.php
User will receive email to his inbox for password resetting. When user open the URL he can see this view to reset the password

You need to chene the action of the form to

First thing you have to do is, change the forgot my password URL
In view\admin\login.blade.php file you can change the existing code to


   Forgot Your Password?

In view\admin you need following files copied from the resources\views\auth
login.blade.php
register.blade.php
password\email.blade.php
password\

You need to configure password broker to work with admin otherwise it will work with default users

in your config\auth.php file you need following code

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


    ],

Now in your AdminForgotPasswordController class you have to specify which password broker you are going to use

protected function broker(){
     return Password::broker('admins');
}

Reset Email Customization

You need to customize reset email otherwise it will have details related to user guard
You can add the following method to your App\Admin.php model

public function sendPasswordResetNotification($token)
{
    $this->notify(new AdminResetPasswordNotification($token));
}

Now you can create the AdminResetPasswordNotification using Artisian command

php artisan make:notification AdminResetPasswordNotification

AdminResetPasswordNotification.php is create inside the Notifications folder

In AdminResetPasswordNotification class, I am going to add instance variable name public $token

And changing the constructor to accept the token value

 public function __construct($token)
 {
        $this->token=$token;
 }

Now changing the toMail() function

  public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->line('You are receiving this email because we received a password reset request for your account.')
                    ->action('Reset Password', url(route("admin.password.reset.token",$this->token)))
                    ->line('If you did not request a password reset, no further action is required.');
    }

Now you can test the Password Reset process