Laravel 5.2 multi auth example using Auth guard from scratch

By Hardik Savani November 5, 2023 Category : Laravel

Multiple authentication is very important in big application of laravel. If you work on large project then you mostly prefer to diferente 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: 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

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 2: Create Models

In this step we have to create two model for User and Admin. I think we have already User.php model will available but make sure just compare code is the same or not. so fist check bellow User.php model.

app/User.php

namespace App;


use Illuminate\Foundation\Auth\User as Authenticatable;


class User extends Authenticatable

{

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = [

'name', 'email', 'password'

];


/**

* The attributes excluded from the model's JSON form.

*

* @var array

*/

protected $hidden = [

'password', 'remember_token',

];

}

app/Admin.php

namespace App;


use Illuminate\Foundation\Auth\User as Authenticatable;


class Admin extends Authenticatable

{

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = [

'name', 'email', 'password'

];


/**

* The attributes excluded from the model's JSON form.

*

* @var array

*/

protected $hidden = [

'password', 'remember_token',

];

}

Step 3: Create Route and Controller

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:

app/Http/routes.php

Route::group(['middleware' => ['web']], function () {

Route::get('web-login', 'Auth\AuthController@webLogin');

Route::post('web-login', ['as'=>'web-login','uses'=>'Auth\AuthController@webLoginPost']);

Route::get('admin-login', 'AdminAuth\AuthController@adminLogin');

Route::post('admin-login', ['as'=>'admin-login','uses'=>'AdminAuth\AuthController@adminLoginPost']);

});

Add bellow code on Auth/AuthController.php file and put bellow code.

app/Http/Controller/Auth/AuthController.php

namespace App\Http\Controllers\Auth;


use App\User;

use Validator;

use App\Http\Controllers\Controller;

use Illuminate\Foundation\Auth\ThrottlesLogins;

use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

use Illuminate\Http\Request;


class AuthController extends Controller

{


use AuthenticatesAndRegistersUsers, ThrottlesLogins;


protected $redirectTo = '/';


/**

* Create a new authentication controller instance.

*

* @return void

*/

public function __construct()

{

$this->middleware('guest', ['except' => 'logout']);

}


/**

* Get a validator for an incoming registration request.

*

* @param array $data

* @return \Illuminate\Contracts\Validation\Validator

*/

protected function validator(array $data)

{

return Validator::make($data, [

'name' => 'required|max:255',

'email' => 'required|email|max:255|unique:users',

'password' => 'required|confirmed|min:6',

]);

}


/**

* Create a new user instance after a valid registration.

*

* @param array $data

* @return User

*/

protected function create(array $data)

{

return User::create([

'name' => $data['name'],

'email' => $data['email'],

'password' => bcrypt($data['password']),

]);

}


public function webLogin()

{

return view('webLogin');

}


public function webLoginPost(Request $request)

{

$this->validate($request, [

'email' => 'required|email',

'password' => 'required',

]);

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

{

$user = auth()->user();

dd($user);

}else{

return back()->with('error','your username and password are wrong.');

}

}

}

Create new folder and AdminAuth and add new AuthController.php folder, put bellow code on that file.

app/Http/Controller/AdminAuth/AuthController.php

namespace App\Http\Controllers\AdminAuth;


use App\Admin;

use Validator;

use App\Http\Controllers\Controller;

use Illuminate\Foundation\Auth\ThrottlesLogins;

use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

use Illuminate\Http\Request;


class AuthController extends Controller

{


use AuthenticatesAndRegistersUsers, ThrottlesLogins;


protected $redirectTo = '/';


/**

* Create a new authentication controller instance.

*

* @return void

*/

public function __construct()

{

$this->middleware('guest', ['except' => 'logout']);

}


/**

* Get a validator for an incoming registration request.

*

* @param array $data

* @return \Illuminate\Contracts\Validation\Validator

*/

protected function validator(array $data)

{

return Validator::make($data, [

'name' => 'required|max:255',

'email' => 'required|email|max:255|unique:users',

'password' => 'required|confirmed|min:6',

]);

}


/**

* Create a new user instance after a valid registration.

*

* @param array $data

* @return User

*/

protected function create(array $data)

{

return Admin::create([

'name' => $data['name'],

'email' => $data['email'],

'password' => bcrypt($data['password']),

]);

}


public function adminLogin()

{

return view('adminLogin');

}


public function adminLoginPost(Request $request)

{

$this->validate($request, [

'email' => 'required|email',

'password' => 'required',

]);

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

{

$user = auth()->guard('admin')->user();

dd($user);

}else{

return back()->with('error','your username and password are wrong.');

}

}

}

Step 4: Create Blade

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/webLogin.blade.php

@extends('layouts.app')


@section('content')

<div class="container">

<div class="row">

<div class="col-md-8 col-md-offset-2">

<div class="panel panel-default">

<div class="panel-heading">Login</div>

<div class="panel-body">

<form class="form-horizontal" role="form" method="POST" action="{{ route('web-login') }}">

{!! csrf_field() !!}


<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">

<label class="col-md-4 control-label">E-Mail Address</label>


<div class="col-md-6">

<input type="email" class="form-control" name="email" value="{{ old('email') }}">

@if ($errors->has('email'))

<span class="help-block">

<strong>{{ $errors->first('email') }}</strong>

</span>

@endif

</div>

</div>


<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">

<label class="col-md-4 control-label">Password</label>


<div class="col-md-6">

<input type="password" class="form-control" name="password">

@if ($errors->has('password'))

<span class="help-block">

<strong>{{ $errors->first('password') }}</strong>

</span>

@endif

</div>

</div>


<div class="form-group">

<div class="col-md-6 col-md-offset-4">

<button type="submit" class="btn btn-primary">

<i class="fa fa-btn fa-sign-in"></i>Login

</button>

<a class="btn btn-link" href="{{ url('/password/reset') }}">Forgot Your Password?</a>

</div>

</div>

</form>

</div>

</div>

</div>

</div>

</div>

@endsection

Ok and also create other file for admin login.

resources/views/adminLogin.blade.php

@extends('layouts.app')


@section('content')

<div class="container">

<div class="row">

<div class="col-md-8 col-md-offset-2">

<div class="panel panel-default">

<div class="panel-heading">Login</div>

<div class="panel-body">

<form class="form-horizontal" role="form" method="POST" action="{{ route('admin-login') }}">

{!! csrf_field() !!}


<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">

<label class="col-md-4 control-label">E-Mail Address</label>


<div class="col-md-6">

<input type="email" class="form-control" name="email" value="{{ old('email') }}">

@if ($errors->has('email'))

<span class="help-block">

<strong>{{ $errors->first('email') }}</strong>

</span>

@endif

</div>

</div>


<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">

<label class="col-md-4 control-label">Password</label>


<div class="col-md-6">

<input type="password" class="form-control" name="password">

@if ($errors->has('password'))

<span class="help-block">

<strong>{{ $errors->first('password') }}</strong>

</span>

@endif

</div>

</div>


<div class="form-group">

<div class="col-md-6 col-md-offset-4">

<button type="submit" class="btn btn-primary">

<i class="fa fa-btn fa-sign-in"></i>Login

</button>

<a class="btn btn-link" href="{{ url('/password/reset') }}">Forgot Your Password?</a>

</div>

</div>

</form>

</div>

</div>

</div>

</div>

</div>

@endsection

Now lets try and see...

Shares