175

I am trying to authenticate users and admin form user table and admin table respectively. I am using the User model as provided by laravel out of the box and created the same for Admin. I have added a guard key and provider key into auth.php.

Guards

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

Providers

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

Routes

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');
});

I have created a directory called AuthAdmin where Laravel's default AuthController.php and PasswordController.php files are present. (Namespace Modified accordingly)

First of all, in Laravel's docs mentioned that how to specify custom guard while authenticating like this which isn't working.
enter image description here

There's another method mentioned in Laravel's docs to use a guard which is not working too.

enter image description here

It would be beneficial if someone could resolve the issues and correct me if I am wrong.

Karl Hill
  • 6,972
  • 3
  • 39
  • 64
imrealashu
  • 4,939
  • 4
  • 13
  • 27
  • Laravel fixed a bug in version 5.2.6. `protected $guard = 'guard_name'` can be used now. – imrealashu Jan 05 '16 at 15:26
  • In Laravel there are many Admin panel generator packages available. I prefer Voyager Admin. Installing them easy and breeze. It may save you ton of code. You just need to understand how it works. Don't reinvent the wheel. [Voyager - The Missing Laravel Admin](https://laravelvoyager.com/) [A Laravel application with Gentelella bootstrap admin tempalte.](https://github.com/FlorientR/laravel-gentelella) – sathish R Jun 27 '17 at 17:04

3 Answers3

203

After lots of digging and lots of questions & answers I have finally managed to work Laravel 5.2 Multi Auth with two table, So I'm writing Answer of my own Question.

How to implement Multi Auth in Laravel 5.2

As Mentioned above. Two table admin and users

Laravel 5.2 has a new artisan command.

php artisan make:auth

it will generate basic login/register route, view and controller for user table.

Make a admin table as users table for simplicity.

Controller For Admin
app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController
(note: I just copied these files from app/Http/Controllers/Auth/AuthController here)

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' => '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');
}  

it will help you to open another login form for admin

creating a middleware for admin

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('/');
    }

    return $next($request);
}

}

register middleware in kernel.php

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

use this middleware in AdminController e.g.,

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()` **Edit - 1** 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() ##Edit 2 Now you can download Laravel 5.2 Multiauth implemented Project http://imrealashu.in/code/laravel/multi-auth-with-laravel-5-2-2/
danronmoon
  • 3,613
  • 5
  • 32
  • 55
imrealashu
  • 4,939
  • 4
  • 13
  • 27
  • thanks a lot man, this was what i was searching for, it worked with a litle bit of modification. thanks a lot +1 for Q and +1 for Ans, wish i could +1 more. thanks a lot.. – rummykhan Feb 02 '16 at 08:22
  • @imrealashu, As I have created project as per your answer. But it generates error of multiple classes with same name. So what about that? If I changes class name for admin auth, then where I need to do changes? – Akshay Vaghasiya Feb 22 '16 at 06:43
  • I'd recommend you to separate two auth controllers with different folder. e.g., `Admin\AuthController.php` and `Users\AuthController.php` or you can keep default `Auth\AuthController.php` intact. and make sure to change the `namespace` accordingly. – imrealashu Feb 22 '16 at 07:46
  • @imrealashu, as I have changed namespace for AdminAuth/AuthController, problem is solved. But I have username for admin and email for user. So what changes need to apply for authentication while login admin? And even I can't get login. – Akshay Vaghasiya Feb 22 '16 at 10:31
  • 1
    can you please also explain how to "Reset Password" for admin guard. – Shoaib Rehan Mar 04 '16 at 06:37
  • yeas sure, give me some time. I'll update the answer. – imrealashu Mar 04 '16 at 09:01
  • 1
    Thanks for the excellent explanation was very useful to me everything. To use the middleware guest, change the RedirectIfAuthenticated.php file the following line: Original:          `if (Auth :: guard ($ guard) -> check ()) { return redirect ('/'); }` After the change:        `if (Auth :: guard ('yourcustomguard') -> check () || Auth :: check ()) { return redirect ('/'); }` – Cristian Meza Mar 29 '16 at 03:06
  • I am trying to make login for admin and user. It works for me with admin but it fails when I try to login user. Any idea why? – Aryan Mar 30 '16 at 12:04
  • @Aryan will you be able to share some of your code ? – imrealashu Mar 30 '16 at 23:14
  • @CristianMeza Glad I could help and appreciate you for noticing me this one you have mentioned above. I will update my answer. – imrealashu Mar 30 '16 at 23:16
  • @imrealashu Using multi auth is it possible to login both admin and user in different tab in same bowser? – Kiren S Apr 04 '16 at 05:25
  • @KirenSiva yeah, it is possible. I have faced some problem in local server like when user tries to log in and if admin is already logged in then admin gets logged out automatically. But when deployed on live server it works fine. – imrealashu Apr 04 '16 at 15:01
  • Hello again friends, I have been presented a problem. The problem is that the routes Auth default user are visible although this log with the admin. Example: I'm logged in as administrator with the route admins/login, but even I can see the path /login of the default user of Laravel and vice versa. Then as I can protect the routes are a user or another when any this log?. Greetings from Chile – Cristian Meza Apr 18 '16 at 09:25
  • Thanks for your answer! But could you please tell me how should I write the `Admin/AuthController@register` function? Thanks! – user5779223 May 17 '16 at 12:06
  • I am just wondering, why did have to spend so much time doing this. Laravel is supposed to be so easy ... [wink, wink] – Jeffz Aug 01 '16 at 22:13
  • 1
    @Jeffz its just because of bad documentation and no working examples on multi-auth.. we expect good documentation and yeah the new cool features on this 5.3 update. – imrealashu Aug 01 '16 at 22:31
  • Can also confirm that this works beautifully on Laravel 5.3! Thanks for the fantastic guide mate.This is probably the only bit of the Laravel documentation that's lacking, and oddly enough if you require it, it's probably one of the most important parts of the entire application – DLMousey Oct 04 '16 at 08:09
  • Hello I have done Multi Auth same way as describe above but every time when I try to login using admin/login after login it redirect to front end side login page say /login not in admin/dashboard please help for same – Naresh Ramoliya Nov 02 '16 at 06:54
  • did you see [this](http://imrealashu.in/code/laravel/multi-auth-with-laravel-5-2-2/#comment-2978994019) post ? I've also included a multi auth implemented repo [link](https://github.com/imrealashu/laravel-multiauth) there. – imrealashu Nov 02 '16 at 07:49
  • I have one question, does it allow to login two different type of users on same browser but on different tabs. i.e in one browser tab simple user is logged in and in another tab admin user. Is it possible? – Parth Vora Dec 07 '16 at 14:02
  • @imrealashu, I have followed all step as per you but logout is not working because Guard was not updated it hold default value. Please tell me – Amit Maan Jan 19 '17 at 13:06
  • I made this setup and this works perfectly fine for me but what I want to ask is that how can stop the auto login right after sign up, as I'm putting the register user option inside the Admin and when I as an Admin register some user it makes that user logged in as well then Admin becomes logged in inside the user. So, I think by changing this feature of auto login my problem will be solved, please suggest how to fix this. – Vikas Meena Jun 02 '17 at 08:38
  • @VikasMeena For that you need to override `register` method of `RegisterUser` trait. Because in register method it logs in user once they complete registration. – imrealashu Jun 04 '17 at 11:26
  • @imrealashu, it is possible to use `user` table for both `admin` and `users`? – Vel Feb 12 '19 at 08:50
  • i tried with `'providers' => [ 'users' => [ 'driver' => 'database', 'table' => 'user', 'model' => App\User::class, ], 'admins' => [ 'driver' => 'database', 'table' => 'user', 'model' => App\Admin::class, ] ],`. But user login not working – Vel Feb 12 '19 at 08:53
2

In case this helps anyone, and this may just be due to my lack of understanding of middleware, here's what I had to do to get this working (in addition to the steps taken by @imrealashu)...

In route.php:

Route::get('/admin', [
  'middleware' => 'admin',
  'uses' => 'AdminController@index'
]);

This is in the web middleware group. Before this I tried putting it in a separate admin middleware group and even in an auth:admin group but this didn't work, it only worked for me when I specified the middleware as admin on the route itself. I have no idea why this is but I hope it saves others from pulling their hair out like I did.

Sworrub Wehttam
  • 528
  • 4
  • 14
  • I downloaded your multi auth zip file replaced with ezisting project files then when I migrate my DB this error show..[Symfony\Component\Console\Exception\RuntimeException] Not enough arguments (missing: "name"). – G Naga Subrahmanyam Oct 31 '16 at 11:14
  • Actually for me admin is logging in but not redirected to admin. After doing this it works can you please tell why's so? I got to register other routes as is it possible with `Route::group(['middleware' => ['admin']], function () { //Admin Routes... });` cause it's not working for me – Leap Hawk Nov 11 '16 at 05:50
1

It's very easy in laravel 5.6. Just go to config/auth.php and add this line in providers array:

'admins' => [
   'driver' => 'database',
   'table' => 'admin_table'
]

Note that we used database for driver not eloquent.

Now add this to guards array:

'admin_guard' => [
   'driver' => 'session',
   'provider' => 'admins'
]

Now we're done! Use this when working with admins table:

Auth::guard('admin_guard')->User();

Cheers.

Sky
  • 3,906
  • 6
  • 48
  • 77