Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 395
A.B.Developer Avatar asked Nov 05 '17 17:11

A.B.Developer


People also ask

Is there multiple authentication in Laravel?

Multiple Authentication in Laravel 5.4 Natively! (Admins + Users) - Part 1 - YouTube Multiple Authentication in Laravel 5.4 Natively! (Admins + Users) - Part 1 If playback doesn't begin shortly, try restarting your device. Videos you watch may be added to the TV's watch history and influence TV recommendations.

How to implement company guard in Laravel?

It's on Laravel 5.2, but it can be easily implemented on Laravel 5.4. Create a model App\Company which extends Authenticatable Class. This model will work as user model which will company guard (in the next step)

How do I scaffold authentication in Laravel?

Laravel provides a quick way to scaffold all of the routes and views you need for authentication using one simple command: This command should be used on fresh applications and will install a layout view, registration and login views, as well as routes for all authentication end-points.

How do I define the AUTH basic middleware in Laravel?

The auth.basic middleware is included with the Laravel framework, so you do not need to define it: Once the middleware has been attached to the route, you will automatically be prompted for credentials when accessing the route in your browser. By default, the auth.basic middleware will use the email column on the user record as the "username".


1 Answers

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()
like image 174
Abid Raza Avatar answered Oct 04 '22 01:10

Abid Raza