Skip to content

Instantly share code, notes, and snippets.

@sniper7kills
Last active June 5, 2019 06:14
Show Gist options
  • Save sniper7kills/a1aa72d00517d4cceb8c813121b1231c to your computer and use it in GitHub Desktop.
Save sniper7kills/a1aa72d00517d4cceb8c813121b1231c to your computer and use it in GitHub Desktop.
Laravel Simple Multi-Model Authentication

This is a simple method of implementing multi-model / guard authentication into laravel using the default laravel authentication structure. (NOTE: passport // API integration not included yet)

  1. php composer make:auth
  2. cp App/User.php App/Admin.php
  3. Edit App/Admin.php and change the class name to Admin
  4. Edit config/auth.php and add the following
...
'guards' => [
...
    'admin' => [
        'driver' => 'session',
        'provider' => 'admin',
    ],
    'admin_api' => [
        'driver' => 'passport',
        'provider' => 'admin',
        'hash' => false,
    ],
],
...
'providers' => [
...
    'admin' => [
        'driver' => 'eloquent',
        'model' => App\Admin::class,
    ],
],
...
'passwords' => [
...
    'admin' => [
        'provider' => 'admin',
        'table' => 'password_resets',
        'expire' => 60,
    ],
],
  1. php make:middleware AuthGuard
  2. Edit app/Http/Middleware/AuthGuard.php to contain the following file.
  3. Edit app\Http\Kernel.php
...
protected $middlewareGroups = [
    'web' => [
...
        \App\Http\Middleware\AuthGuard::class,
    ],
...
<?php
namespace App\Http\Middleware;
use App\Admin;
use Closure;
use Illuminate\Support\Facades\Auth;
class AuthGuard
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if($request->session()->has('guard'))
config(['auth.defaults.guard' => $request->session()->get('guard','users')]);
if($request->is('login') && $request->isMethod('post')){
if(Admin::where('email',$request->get('email'))->count() > 0){
config(['auth.defaults.guard' => 'admin']);
$request->session()->put('guard','admin');
}
}
return $next($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment