Multi Auth With Laravel 5.2
Programming #Laravel

How to implement Multi Auth in Larvel 5.2

Lets start with two tables admin and users.
Laravel 5.2 comes with new artisan command which will generate route, controller and views for users table.

php artisan make:auth

After this command your controller have these files.

app/Http/Controllers/Auth/AuthController
app/Http/Controllers/Auth/PasswordController

Now make an admin table. ( For simplicity you can make same migration for admin as users table has. )

Controller for admin

app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController

copied from app/Http/Controllers/Auth/* (Make sure that you’ve changed the namespace)

Now Lets edit the config/auth.php

//Authenticating guards
'guards' => [
    'user' =>[
        'driver' => 'session',
        'provider' => 'user',
    ],
    'admin' => [
        'driver' => 'session',
        'provider' => 'admin',
    ],
],  

//User Providers
'providers' => [
    'user' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
    'admin' => [
        'driver' => 'eloquent',
        'model' => App\Admin::class,
    ]
],  

//Resetting Password  
'passwords' => [
    'clients' => [
        'provider' => 'client',
        'email' => 'auth.emails.password',
        'table' => 'password_resets',
        'expire' => 60,
    ],
    'admins' => [
        'provider' => 'admin',
        'email' => 'admin.auth.emails.password',
        'table' => 'password_resets',
        'expire' => 60,
    ],
],

route.php

Route::group(['middleware' => ['web']], function () {
    //Login Routes...
    Route::get('/admin/login','AdminAuth\AuthController@showLoginForm');
    Route::post('/admin/login','AdminAuth\AuthController@login');
    Route::get('/admin/logout','AdminAuth\AuthController@logout');

    // Registration Routes...
    Route::get('admin/register', 'AdminAuth\AuthController@showRegistrationForm');
    Route::post('admin/register', 'AdminAuth\AuthController@register');

    Route::get('/admin', 'AdminController@index');

});

AdminAuth\AuthController.php

Add two methods and specify $redirectTo and $guard

protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
    if (view()->exists('auth.authenticate')) {
        return view('auth.authenticate');
    }

    return view('admin.auth.login');
}
public function showRegistrationForm()
{
    return view('admin.auth.register');
}  

Creating a middleware for admin

{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @param  string|null  $guard
 * @return mixed
 */
public function handle($request, Closure $next, $guard = 'admin')
{
    if (!Auth::guard($guard)->check()) {
        return redirect('/');
    }

    return $next($request);
    }
}

Register middleware in kernel.php

protected $routeMiddleware = [
    'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];

Use this middleware in AdminController.php e.g.,

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;

class AdminController extends Controller
{
    public function __construct(){
        $this->middleware('admin');
   }
public function index(){
        return view('admin.dashboard');
    }
}

That’s all needed to make it working and also to get json of authenticated admin use Auth::guard('admin')->user()

NOTE

We can access authenticated user directly using Auth::user() but if you have two authentication table then you have to use

Auth::guard('guard_name')->user() for logout

Auth::guard('guard_name')->user()->logout()

for authenticated user json Auth::guard('guard_name')->user()

For Password Reset In file App/Http/Controllers/AdminAuth/PasswordController.php add two protected variables

protected $guard = 'admin'; //For guard
protected $broker = 'admins'; //For letting laravel know which config you're going to use for resetting password

And add three public method showResetForm, getEmail(), showLinkRequestForm

public function getEmail()
{
    return $this->showLinkRequestForm();
}

public function showLinkRequestForm()
{
    if (property_exists($this, 'linkRequestView')) {
        return view($this->linkRequestView);
    }

    if (view()->exists('admin.auth.passwords.email')) {
        return view('admin.auth.passwords.email');
    }

    return view('admin.auth.password');
}

public function showResetForm(Request $request, $token = null)
{

    if (is_null($token)) {
        return $this->getEmail();
    }
    $email = $request->input('email');

    if (property_exists($this, 'resetView')) {
        return view($this->resetView)->with(compact('token', 'email'));
    }

    if (view()->exists('admin.auth.passwords.reset')) {
        return view('admin.auth.passwords.reset')->with(compact('token', 'email'));
    }

    return view('admin.passwords.auth.reset')->with(compact('token', 'email'));
}

These functions are copied from ResetsPasswords trait. You can simply create a trait as well in the same AuthAdmin directory if you want to.

Now Update add three routes in your route.php

Route::post('admin/password/email','AdminAuth\PasswordController@sendResetLinkEmail');
Route::post('admin/password/reset','AdminAuth\PasswordController@reset');
Route::get('admin/password/reset/{token?}','AdminAuth\PasswordController@showResetForm');

Don’t forget to change url of action attribute on each view files. admin.auth.emails.password.blade.php, admin.auth.passwords.email.blade.php and admin.auth.passwords.reset.blade.php in your views directory.

Checkout Github Repo

2 minutes read 6th Jan 2016

About

A entrepreneur, running an early stage venture, VizitDoc and a MVP-First Service Based Companay ThecodeWork.

A dreamer, having care for alternative education.

Archives - 1

  • Code

    20 Articles

    List of code snippet and articles I wrote when I started blogging in early 2016 😃

Codementor badge