假设我有两个不同的模型和表,名为public class MyApp extends Application {
public static boolean isDebuggable;
public void onCreate() {
super.onCreate();
isDebuggable = (0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE));
FirebaseCrash.setCrashCollectionEnabled(!isDebuggable);
}
}
和user
。
如您所知,laravel使用company
模型来管理身份验证。但是因为我有两种不同的型号我想要分别管理它们。
我使用的是laravel 5.4,我不知道怎么做。
答案 0 :(得分:7)
如果您正在谈论多个身份验证系统,那么您必须创建多个警卫才能实现这一目标。
对同一个问题有很好的答案。
Can anyone explain Laravel 5.2 Multi Auth with example
它在Laravel 5.2上,但它可以在Laravel 5.4上轻松实现。
创建扩展可验证类的模型 App \ Company 。此模型将作为用户模型工作,公司保护(下一步)
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User 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',
];
}
为模型 App \ Company 创建一名警卫和提供者。
// 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' => App\User::class,
],
'company' => [
'driver' => 'eloquent',
'model' => App\Company::class,
]
],
现在您可以根据不同的警卫找到用户。
$user = Auth::guard('company')->user();
// Or...
$user = auth()->guard('company')->user();
dd($user);
现在为公司 App \ Http \ Controllers \ Auth \ CompanyLoginController 创建Auth控制器,与 Auth \ LoginController 相同。 指定 $ redirectTo 和后卫
//Auth\ComapnyLoginController.php
protected $redirectTo = '/comapany';
protected $guard = 'comapany';
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('comapany.auth.login');
}
现在为用户创建登录表单 - company.auth.login视图与用户的登录表单相同。
现在创建路线
//Login Routes...
Route::group(['prefix'=>'company', 'middleware'=>'company'], function(){
Route::get('/login','Auth\CompanyLoginController@showLoginForm');
Route::post('/login','Auth\CompanyLoginController@login');
// ...
// rest of the company dashboard and other links
// ...
Route::get('/logout','Auth\CompanyLoginController@logout');
});
为公司创建中间件
class RedirectIfNotCompany
{
/**
* 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 = 'company')
{
if (!Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}
并将其注册到kernal.php
protected $routeMiddleware = [
'company' => \App\Http\Middleware\RedirectIfNotCompany::class,
];
这就是你需要的一切。 以守卫名称访问用户
Auth::guard('company')->user()