Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mr.teapot's avatar

Laravel 5.3 Multi Auth - how can I make it work?

Hello!

I'm new to Laravel and I would like to find out how to how make multiple authenticable user models. I've searched a lot and haven't found anything that works well. I'm using 5.3 now and there always seems to be a different directory structure from what I have in every tutorial I find. (2 files instead of 4 in the AuthController-folder for example). This makes it messy for me.

I would like to have an employee and customer model, and each can login from a different view (employee/login and customer/login). Another question I have is how to use the Auth-facade with multi auth. What will Auth::user() return depending on which type is signed in?

I don't think it makes sense to have one user model and then employee/customer roles since they will store completely different information on the object and have other relations.

Do you know any good tutorials for this and how to implement this in laravel 5.3? What are the best practices?

Thanks in advance. All answers are very appreciated.

Kind regards, Teapot

0 likes
32 replies
lchandrakanth's avatar

Same issue.. Please help me out...

If we create an AdminAuthController, its always accessing the user table only...

jlrdw's avatar

Same table can be used. An Admin and a user can be in same table for sake of login. That's where roles and permissions fields come in. A little tricky, but write it all out with pencil and paper it will make more sense.

1 like
Hesto's avatar

@jlrdw I don't agree with you. I always make another tables for Users and for Employees. Only Employees can login into admin panel, and users can login into another front interface. User and Employee model is always realy different, for example Employee would have Work Schedule and Users (Customers) don't. And thats why you should keep them separately. Of course roles and permissions can work for both models.

1 like
arrowdesign's avatar

Setup your config.auth like 5.2 Copy the laravel 5.3 auth controllers and add the Auth facade like this,

namespace Modules\Core\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Support\Facades\Auth;

class LoginController extends Controller { use AuthenticatesUsers; protected $redirectTo = '/'; public function __construct() { $this->middleware('guest', ['except' => 'logout']); }

protected function guard() { return Auth::guard('user'); }

protected function showLoginForm() { return view('auth.login'); } }

Route

$router->group(['prefix' => Config::get('cms.admin'),'middleware' => ['guest:user']], function ($router) { # Login $router->get('/', ['as'=>'user.auth', 'uses'=>'LoginController@showLoginForm']); $router->post('/', 'LoginController@login')->name('user.login'); });

probably there's a better solution but it works.

protected function unauthenticated($request, AuthenticationException $exception)
{
    $use = false;
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }
    
    $middlewares = $request->route()->middleware();
    foreach ($middlewares as $middleware)
    {
        if (str_is('auth:*', $middleware))
        {   # Set
            $use = substr($middleware, 5);
        }
    }
    
    if ($use)
    {
        return redirect()->route($use.'.auth');
    } 
    
    return response()->view('errors.500', [], 500);
}

Works without problems with two authentications.

1 like
mr.teapot's avatar

Thanks for all the answers!

I think I managed to get it to work by overriding the AuthenticatesUsers trait in the auth controllers, so I can show specific views for my other authenticable model. And updating the auth.php config file ofc.

Modifying the trait itself is a problem when you update and such. But what is wrong with just overriding it with my own methods? What do you say about the @Hesto? Any future headaches?

I think multi auth is a very important feature, all of my projects require it. I believe there should be an artisan make-command for it. Maybe you should be able to type "php artisan make:model Customer --auth" and get authentication for that model out of the box? What do you think?

Hesto's avatar

@mr.teapot ofc you can override guard() method. It was just late when i posted that answer and i didnt see the simplest way. I will update my post in 1 hour. I also forget about additional middlewere which you need, so ill add it too. Btw i am working on multi auth composer package, becouse i am tired of repeating it over and over in every project.

1 like
Laraveldeep's avatar

Hi,

I am new to Laravel too. My requirement is also multi authentication and thinking of making separate app for each (where I can separate the session name for each app to avoid conflict). If everything can be done in single app with view change, much better.

But thinking from session point of view, I can see the logout problem on multi auth in single app, because session is same.

So user have to login either as employee or customer. Even if we manage to let them login from both, when one account logs out it will also logout from another account (supposing we destroy the session during logout process).

So just curious if solution provided by @Hesto is good to avoid conflict like that.

What I know is we can configure only one session name per app.

Currently trying to understand these: https://github.com/ollieread/multiauth/ http://ollieread.com/blog/2014/03/18/a-simplified-laravel-acl/

Thanks!

sjarifhd's avatar

Hello @Hesto I tried your multi-auth package, but getting this error:

Installation failed, reverting ./composer.json to its original content.
[RuntimeException]                                                     
Could not scan for classes inside "/home/rieftux/workspace/lrvl-multi/vendor/hesto/multi-auth/src/commands" which does not appear to be a file nor a folder
Hesto's avatar

@sjarifhd Looks like composer bug? Maybe update composer to latest version or try to install another package to check if it works. Look into your ./composer.json and check if there is latest version of hesto/multi-auth.

"hesto/multi-auth": ">=1.0.4"
sjarifhd's avatar

I have updated my composer to v-1.2, and also try to manually add require to composer.json file. And try to reinstall or update composer again. But I get the same error:

[RuntimeException]                                                                                          
Could not scan for classes inside "/home/rieftux/workspace/lrvl-multi/vendor/hesto/multi-auth/src/commands" which does not appear to be a file nor a folder 
jekinney's avatar

More then one user table versus roles and/or permission not efficient and confusing as seen above. Yes some use cases but I haven't seen a valid one yet.

Had one client who insisted on it. Some douche told him better security. Same db, same authentications. Same checks as if it was one table with roles. If user has this role. Access. Or if user is logged in with this guard access.

Thank god for change orders. I clearly documented the cons and possible issues. Had him sign and implemented it. Month later email blows up. He can't stand loggin in and out to switch between frontend and back. Guess who got paid to implement the dumb feature AND got paid double to unimploment?

But guess who he's going to trust next time? The douche that built the main part of the site that cost him $2000 or me who would have saved him $2500 plus the hassle and frustration? Guess that douche lost a client.

Wait!!! Please implement it so I can get more clients and charge $2000 for 2 hrs of work.

Hesto's avatar

@jekinney the easiest example is e-commerce. I can't even imagine how unprofessional is one form for both users and admins for that case. In fact almost every business system need multi auth because we have admin panel. Show me one popular open source CMS with single table login.

1 like
jekinney's avatar

@Hesto

Magento community edition. Number 1 open source e commerce cms.

2.0 does have an admin table but it's linked to the main customer table. It requires you to only enter a password to access the backend. Which with laravels auth you can require auth once for the same effect.

But a cms is so generic to fit many needs its almost like comparing apples to oranges. Can an ecommerce site be built with half the 333 tables? I hope so.

Hesto's avatar

@jekinney What if you need another logic in employees (admins) and users? For example shopping carts should belongs to users, but if they belongs to employees its weird right? Employees could have any working schedules but users dont need it. In my opinion that big things like users and employees should be sapareted.

jekinney's avatar

@Hesto

Like I said, there are use cases, I just never have come across one that can't be implemented with ACL or some modified version of an ACL.

My theroy is: most users want one login. Simple and easy. Many people now days won't register with a site unless they have too. Hence why most sites implement Facebook etc one click register and login.

Secondly users table should only define the basics of what you need to define a user. The other data should be else where. Specifically if you're using Laravel and auth(). Otherwise your loading to much data every time you auth()->user(). Instead I use other tables for data not necessarily required. This allows for more of a dynamic fell and less chance later you need to modify the users table.

Pretty easy if not easier to lock down routes via middle wear making sure a user has a role and/or permission to access it or perform an action. You can even have the user re type their password as another layer too with auth::once.

For me makes no sense to have a employee users when you can assign a role of employee etc. then the user is actually still defined as a member, guest, employee, customer etc.

BUT I do see on paper that having multiple tables would benefit if you had a million users and on paper.

Faster queries and less confusion. But to counter that even a lot of sites build database bridges to popular forum software to eliminate the multiple registration and logins. Phpbb2 (old school) has these bridges for most cms at the time. Like Wordpress, xoops, e107, Drupal etc. all to use or simulate one auth table.

Hesto's avatar

@jekinney with multi-auth i use roles and permissions too. Employee could be manager, cheef or accountant etc. You know, i feel you have never built enough big system to appreciate multi-auth. Laravel is all about Keep It Simple Stupid (KISS) so if your projects don't need multi-auth just don't use it. But you can't tell people to not use multi-auth because YOU don't need it. Many people need it to their projects including me.

jekinney's avatar

@Hesto actually I can say that :). If people aren't smart enough to realize it an option and opinion then oh well. At the same time like I stated each reply I am sure there are use cases, I never have seen the pros out way the cons. That's on you trying to defend your point of view.

I'm sure one of these days it might be a valid requirement for a project I'm working on.

aritz's avatar

@Hesto i have tried to do multi auth like you said but i'm getting in trouble with the logout function.

If i log in in two areas i have created (admin site and normal site) when i log out in one site the other session also logs out to.

larafever's avatar

@Hesto i think i have a solution for user/admin auth from different models and views with each login view protection after auth check......................................................

first go the CONFIG->AUTH.PHP and the following code in the GUARDS ARRAY

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

tthen in the PROVIDERS ARRAY in AUTH.PHP add

  'admins' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ]

** note: the model can be changed to table then you specify you table name in the db or you can still use the model then specify your model for your admin

then in your ADMIN model use this

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class Admin extends Authenticatable
{

}

you have to create a middleware for your admin pages/routes you can use this to protect your login page and after login pages...


<?php

namespace App\Http\Middleware;

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

class AdminGuard
{
    /**
     * 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)->guest()) {
            if ($request->ajax() || $request->wantsJson())
                return response('Unauthorized.', 401);
                return redirect()->route('admin');//redirect to admin login;
            }
        return $next($request);
    }
}

then you can use a redirect if authenticated already to admin dashboard


<?php

namespace App\Http\Middleware;

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

class AdminRedirect
{
    /**
     * 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()->route('add');
        }

        return $next($request);
    }
}

new protected $routeMiddleware will look like

    protected $routeMiddleware = [
        'admin' => \App\Http\Middleware\AdminGuard::class,//protect guest routes
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'adminguest' => \App\Http\Middleware\AdminRedirect::class,//protect admin routes
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];

in your controller you can use a simple auth::attempt to log your admin in

        if (Auth::guard('admin')->attempt(['username'=>$request['username'],'password'=>$request['password']]))
          return redirect()->route('add');
          return redirect()->back();

***NOTE THAT AFTER ADMIN LOGIN OR AUTH::ATTEMPT == TRUE, USER LOGIN ROUTE IS STILL ACCESSIBLE BUT PROTECTED AND ALL ROUTES UNDER THE USER/AUTH MIDDLEWARE IS STILL PROTECTED

aritz's avatar

@hesto i've seen it but you have to use user auth and admin auth mandatory? I've tried to use only an admin controler for admin site and normal auth for user site. In this case when i log out from user site i get logged out also from admin site.

aritz's avatar

@Hesto i've tried to use your package and still have the same problem. I've done two authentifications for admin and user. When i am loged in in both and i log out from one of then the two sessions get logged out.

aritz's avatar

Is OK to use this package in production site? Or only for development?

Next

Please or to participate in this conversation.