Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

php - Two different models for authentication in laravel 5.4

Suppose I have two different models and tables named user and company.

As you know laravel uses User model to manage Authentication. but beacause I have two different model I want can manage them separately.

I'm using laravel 5.4 and I do not know how can do that.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

  1. 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',
        ];
    
    }
    
  2. 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);
  1. 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.

  1. 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');
    });
    
  2. 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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...