If you are talking about multiple authentication system, then you have to create multiple guards to achieve that.
There is nice answer to the same question.
Can anyone explain Laravel 5.2 Multi Auth with example
It's on Laravel 5.2, but it can be easily implemented on Laravel 5.4.
Create a model AppCompany which extends Authenticatable Class. This model will work as user model which will company guard (in the next step)
namespace App;
use IlluminateNotificationsNotifiable;
use IlluminateFoundationAuthUser as Authenticatable;
class Company extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
Create an guard and a provider for model AppCompany.
// Authenticating guards and providers
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'company' => [
'driver' => 'session',
'provider' => 'company',
],
],
// Providers
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => AppUser::class,
],
'company' => [
'driver' => 'eloquent',
'model' => AppCompany::class,
]
],
Now you can find user according to the different guards.
$user = Auth::guard('company')->user();
// Or...
$user = auth()->guard('company')->user();
dd($user);
Now create Auth controller for Company AppHttpControllersAuthCompanyLoginController same as AuthLoginController.
Specify $redirectTo and guard
//AuthComapnyLoginController.php
protected $redirectTo = '/comapany';
protected $guard = 'comapany';
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('comapany.auth.login');
}
now create login form for user - company.auth.login view same as user's login form.
Now create routes
//Login Routes...
Route::group(['prefix'=>'company', 'middleware'=>'company'], function(){
Route::get('/login','AuthCompanyLoginController@showLoginForm');
Route::post('/login','AuthCompanyLoginController@login');
// ...
// rest of the company dashboard and other links
// ...
Route::get('/logout','AuthCompanyLoginController@logout');
});
Create a middleware for company
class RedirectIfNotCompany
{
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = 'company')
{
if (!Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}
and register it to kernal.php
protected $routeMiddleware = [
'company' => AppHttpMiddlewareRedirectIfNotCompany::class,
];
And thats all you need.
Access user by the name of guard
Auth::guard('company')->user()
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…