4

Does anyone know how to use multi authenticate in laravel 5.2 !
I want to use It but I don't know how ?
does anyone has a tutorial or project setting up multi authentication?

bobD
  • 857
  • 2
  • 7
  • 17
Toàn Tam
  • 91
  • 1
  • 1
  • 9

3 Answers3

27

You need two tables users and admins Run command following command to create built in auth

php artisan make:auth

Two models Users(Already exist) and Admin

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class Admin extends Authenticatable
{
 
}

Now open config/auth.php and make the following changes

'guards' => [
        'web' => [
            'driver' => 'session',
            '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,
        ],
    ],

Create a new Middleware RedirectIfNotAdmin

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class RedirectIfNotAdmin
{
    /**
     * 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('/admin/login');
  }
 
  return $next($request);
 }
}

Changes in Kernel.php

protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
  \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
 ];


protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            //\Illuminate\Session\Middleware\StartSession::class,
            //\Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],
  
        'api' => [
            'throttle:60,1',
        ],
    ];


protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
  'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
    ];

Create a new folder Http/Controller/Adminauth and copy the files from Http/Controller/Auth folder

Open the file Http/Controller/Adminauth/AuthController.php and make the following changes

<?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 Auth;

class AuthController extends Controller
{
    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    protected $redirectTo = '/admin';
 protected $guard = 'admin';
 
 public function showLoginForm()
 {
  if (Auth::guard('admin')->check())
  {
   return redirect('/admin');
  }
  
  return view('admin.auth.login');
 }
 
 public function showRegistrationForm()
 {
  return view('admin.auth.register');
 }
 
 public function resetPassword()
 {
  return view('admin.auth.passwords.email');
 }
 
 public function logout(){
  Auth::guard('admin')->logout();
  return redirect('/admin/login');
 }
}

Create new folder Http/Controller/admin, copy Controller.php file in the folder from Http/Controller/

create new file Http/Controller/admin/employee.php

<?php

namespace App\Http\Controllers\admin;


use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Auth;
use App\Admin;

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

move to resources/views create new folder resources/views/admin copy

resources/views/auth, resources/views/layouts & resources/views/home.blade.php

and post into resources/views/admin and open the each file in admin folder and add admin before each path, Now the path should look like

@extends('admin.layouts.app')

and your Http/routes.php look like

<?php
Route::get('/', function () {
    return view('welcome');
});

Route::get('/admin/login','Adminauth\AuthController@showLoginForm');
Route::post('/admin/login','Adminauth\AuthController@login');
Route::get('/admin/password/reset','Adminauth\PasswordController@resetPassword');

Route::group(['middleware' => ['admin']], function () {
    //Login Routes...
    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', 'Admin\Employee@index');
});



Route::group(['middleware' => 'web'], function () {
    Route::auth();
 Route::get('/home', 'HomeController@index');
 
 
});

Thats it open your site in browser and check and for admin yoursiteurl/admin

Enjoy....

Shoaib Rehan
  • 495
  • 6
  • 16
  • Thanks for this, it was great, one thing I am finding though is that the "/admin/logout" route is being overridden by my "/" route in 'web'. So that it redirects straight to "/" instead of carrying out the work in "/admin/logout". Is there a reason for that behaviour? – David G Apr 02 '16 at 15:00
  • Thanks for great tutorial. The only problem is that the routes Auth default user are visible although this log with the admin. Example: I'm logged in as administrator through the route admins/login, but even I can see the path /login of the default user of Laravel and vice versa. As I can fix that? Greetings from Chile – Cristian Meza Apr 18 '16 at 09:08
  • i am getting this error when calling /admin/password/reset "ErrorException in ResetsPasswords.php line 252: Missing argument 1 for App\Http\Controllers\Adminauth\PasswordController::resetPassword()" – Khan Muhammad May 18 '16 at 08:15
6

First, we create two models: user and admin

Then, we update the config/auth.php file:

return [
    'defaults' => [
        'guard' => 'user',
        'passwords' => 'user',
    ],

    'guards' => [
        'user' => [
            'driver' => 'session',
            'provider' => 'user',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admin',
        ],
    ],
    'providers' => [
        'user' => [
            'driver' => 'eloquent',
            'model' => 'App\User',
        ],
        'admin' => [
            'driver' => 'eloquent',
            'model' => 'App\Admin',
        ],
    ],
    'passwords' => [
        'user' => [
            'provider' => 'user',
            'email' => 'auth.emails.password',
            'table' => 'password_resets',
            'expire' => 60,
        ],
        'admin' => [
            'provider' => 'admin',
            'email' => 'auth.emails.password',
            'table' => 'password_resets',
            'expire' => 60,
        ]
    ]
];

Now, modify the app/Http/kernel.php file:

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class
];

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class      
    ],
    'api' => [
        'throttle:60,1',
    ],
];

Create LoginController and set the following code in it.

Note: You have to create login pages for 'user' as well as 'admin'. You then have to submit login form requests to the appropriate controller function i.e. userLogin() or adminLogin().

namespace App\Http\Controllers;

use Auth, Input;
use App\User;
use App\Admin;

class LoginController extends Controller
{
    public function userLogin(){
        $input = Input::all();
        if(count($input) > 0){
            $auth = auth()->guard('user');

            $credentials = [
                'email' =>  $input['email'],
                'password' =>  $input['password'],
            ];

            if ($auth->attempt($credentials)) {
                return redirect()->action('LoginController@profile');
            } else {
                echo 'Error';
            }
        } else {
            return view('user.login');
        }
    }

    public function adminLogin(){
        $input = Input::all();
        if(count($input) > 0){
            $auth = auth()->guard('admin');

            $credentials = [
                'email' =>  $input['email'],
                'password' =>  $input['password'],
            ];

            if ($auth->attempt($credentials)) {
                 return redirect()->action('LoginController@profile');                     
            } else {
                echo 'Error';
            }
        } else {
            return view('admin.login');
        }
    }

    public function profile(){
        if(auth()->guard('admin')->check()){
             pr(auth()->guard('admin')->user()->toArray());
        }         
        if(auth()->guard('user')->check()){
            pr(auth()->guard('user')->user()->toArray());
        } 
    }
}
Jamal
  • 747
  • 7
  • 22
  • 31
  • How to use multi auth with default AuthController. can you make me correct. I have implemented and its working fine for user table however its authenticating admin from admin table but not creating session for admin. http://stackoverflow.com/questions/34614753/can-anyone-explain-laravel-5-2-multi-auth-with-example – imrealashu Jan 12 '16 at 16:54
  • I am getting error: Authentication user provider [] is not defined. – Shoaib Rehan Mar 03 '16 at 09:24
  • `auth()->guard('admin')->user()` returns null – Mo Al Waili Mar 12 '16 at 11:59
0

In most cases I just add a field to the user table called usertype and pass appropriate values like 0=admin, 1=user etc.

This approach helps in avoiding the unnecessary headache of creating different user roles or types.

Though this may not sound ideal, but helps in saving lots of time.