How to create multiple authentication in Laravel 5.6?

July 28, 2018 | Category : Laravel 5.6 Laravel 5 Laravel PHP

Hi developer,

In this article, i will let you know how to create multi auth using guard in laravel 5.6. here i will give you step by step tutorial for multiple authentication in Laravel 5.6 application.

Multiple authentication is very important in big application of laravel 5.6. If you work on large web application then you mostly prefer to different tables, like you always prefer "users" table for site user registration and "admins" table for admin user that way make strong security. we always use Auth for making user authentication but you have question how to make admins with auth then you can do easily by following step.

Step 1: Create Migration for users and admins

In first step, we need to create users and admins table so first create migration like as bellow migration code:

User Migration:

<?php

use Illuminate\Support\Facades\Schema;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('users', function (Blueprint $table) {

$table->increments('id');

$table->string('name');

$table->string('email');

$table->string('password');

$table->rememberToken();

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('users');

}

}

Admin Migration:

<?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('name');

$table->string('email');

$table->string('password');

$table->rememberToken();

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('admins');

}

}

Step 2: Create User and Admin Model

After creating users and admins table, we need to create User and Admin Model so create both model with given path.

app/User.php

<?php

namespace App;

use Illuminate\Notifications\Notifiable;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User 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',

];

}

app/Admin.php

<?php

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',

];

}

Step 3: Auth Config Setting

In this step we will add new admin guard from auth.php file of config directory. so first open auth.php file and add bellow code.

config/auth.php

<?php

return [

'defaults' => [

'guard' => 'web',

'passwords' => 'users',

],

'guards' => [

'web' => [

'driver' => 'session',

'provider' => 'users',

],

'api' => [

'driver' => 'token',

'provider' => 'users',

],

'admin' => [

'driver' => 'session',

'provider' => 'admins',

],

],

'providers' => [

'users' => [

'driver' => 'eloquent',

'model' => App\User::class,

],

'admins' => [

'driver' => 'eloquent',

'model' => App\Admin::class,

]

],

'passwords' => [

'users' => [

'provider' => 'users',

'email' => 'auth.emails.password',

'table' => 'password_resets',

'expire' => 60,

],

'admins' => [

'provider' => 'admins',

'email' => 'auth.emails.password',

'table' => 'password_resets',

'expire' => 60,

],

],

];

Step 4: Create Default Auth

laravel 5.6 provide default auth, so we will create default auth system by following command:

php artisan make:auth

Step 5: Create Route

Ok, in this step we will create route for multi auth example for user and admin. so first add bellow route on routes.php file:

routes/web.php

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::get('admin-login', 'Auth\AdminLoginController@showLoginForm');

Route::post('admin-login', ['as'=>'admin-login','uses'=>'Auth\AdminLoginController@login']);

Step 6: Create Controller

In this step, we have to write code on controller, So we require two controller. But we don't need to touch default LoginController, We will just create one new for admin and write code for that.

app/Http/Controller/Auth/LoginController.php

<?php

namespace App\Http\Controllers\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 = '/home';

/**

* Create a new controller instance.

*

* @return void

*/

public function __construct()

{

$this->middleware('guest')->except('logout');

}

}

app/Http/Controller/Auth/AdminLoginController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;

use Illuminate\Foundation\Auth\AuthenticatesUsers;

use Illuminate\Http\Request;

class AdminLoginController 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;

protected $guard = 'admin';

/**

* Where to redirect users after login.

*

* @var string

*/

protected $redirectTo = '/home';

/**

* Create a new controller instance.

*

* @return void

*/

public function __construct()

{

$this->middleware('guest')->except('logout');

}

public function showLoginForm()

{

return view('auth.adminLogin');

}

public function login(Request $request)

{

if (auth()->guard('admin')->attempt(['email' => $request->email, 'password' => $request->password])) {

dd(auth()->guard('admin')->user());

}

return back()->withErrors(['email' => 'Email or password are wrong.']);

}

}

Step 7: Create Blade Files

In last step we have to create just two view for login user and other for login admin so let's create file webLogin.blade.php file and put bellow code:

resources/views/auth/adminLogin.blade.php

@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') }}">

@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

Now you can check it....