Ahmad Badpey
Ahmad Badpey

Reputation: 6612

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.

Upvotes: 8

Views: 9500

Answers (1)

Abid Raza
Abid Raza

Reputation: 755

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 App\Company which extends Authenticatable Class. This model will work as user model which will company guard (in the next step)

    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',
        ];
    
    }
    
  2. Create an guard and a provider for model 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,
        ]
    ],
    

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 App\Http\Controllers\Auth\CompanyLoginController same as Auth\LoginController. Specify $redirectTo and guard

    //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');
    }
    

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','Auth\CompanyLoginController@showLoginForm');
        Route::post('/login','Auth\CompanyLoginController@login');
        // ...
        // rest of the company dashboard and other links
        // ...
        Route::get('/logout','Auth\CompanyLoginController@logout');
    });
    
  2. Create a middleware for company

    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);
        }
    }
    

    and register it to kernal.php

    protected $routeMiddleware = [
        'company' => \App\Http\Middleware\RedirectIfNotCompany::class,
    ];
    

And thats all you need. Access user by the name of guard

Auth::guard('company')->user()

Upvotes: 17

Related Questions