Authenticate users from more than two tables in laravel 5

31,995

Solution 1

First create Admin Authenticatable in Illuminate\Foundation\Auth like

    <?php

namespace Illuminate\Foundation\Auth;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

    class Admin extends Model implements
        AuthenticatableContract,
        AuthorizableContract,
        CanResetPasswordContract
    {
        use Authenticatable, Authorizable, CanResetPassword;
    }

Then create Admin Model by extending Authenticatable Admin Model :-

  <?php
namespace App;
use Illuminate\Foundation\Auth\Admin as Authenticatable;

class Admin extends Authenticatable
{
    /**
     * 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',
    ];
}

After that you need to modify config/auth.php like below Add in providers array

'admins' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ], 

and Add in guards array.

 'user' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
 'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],

Now to authenticate from user table

 if (Auth::guard('user')->attempt(['email' => $email, 'password' => $password])) {
        $details = Auth::guard('user')->user();
        $user = $details['original'];
        return $user;
    } else {
        return 'auth fail';
    }

And to authenticate from Admin table

 if (Auth::guard('admin')->attempt(['email' => $email, 'password' => $password])) {
        $details = Auth::guard('admin')->user();
        $user = $details['original'];
        return $user;
    } else {
        return 'auth fail';
    }

Solution 2

You could setup multiple authentication guards, with each one having a different provider. The providers define the table or model to be used.

In config/auth.php you setup the providers as follows and you also setup corresponding guards for each of those providers:

'providers' => [
    'users'  => [
        'driver' => 'eloquent',
        'model'  => App\User::class,
    ],
    'managers'  => [
        'driver' => 'eloquent',
        'model'  => App\Manager::class,
    ],
    'admins'  => [
        'driver' => 'eloquent',
        'model'  => App\Admin::class,
    ]
]

Then you can authenticate like this:

Auth::attempt($credentials) // use default guard for simple users
Auth::guard('manager')->attempt($credentials)
Auth::guard('admin')->attempt($credentials)

Check out the docs here.

Solution 3

Try my idea if you want to. I'm expecting that different table has different users. Because it won't work if you have the same user in other tables.

  1. Choose your priority table (e.g. users)
  2. Add the condition
    • if(Auth::user(attempt(...))
    • elseif(Auth::manager(attempt(...))
    • elseif(Auth::admins(attempt(...)))

Note: Your priority table here is users, then if the user doesn't exists in that table, it will try the managers table, then if still doesn't exists, it will check the admins table, otherwise (use else) return a message error.

Other option:

Other option is to use this package sarav/laravel-multiauth. You can follow this thread. How to use authentication for multiple tables in Laravel 5 for more information.

More Reference:

https://laracasts.com/discuss/channels/general-discussion/using-laravel-auth-for-multiple-tables?page=1

Can anyone explain Laravel 5.2 Multi Auth with example

https://laracasts.com/discuss/channels/laravel/52-auth-multiple-tables?page=1

Solution 4

Create a model for managers table and admins table. This model should extend Illuminate\Foundation\Auth\User

In config/auth.php,

Add to the providers array:

'managers' => [
    'driver' => 'eloquent',
    'model' => App\Manager::class,
 ],

Add to the guards array:

'web_manager' => [
    'driver' => 'session',
    'provider' => 'managers',
 ],

Then. in LoginController (create one for manager using php artisan make:auth) use the trait Illuminate\Foundation\Auth\AuthenticatesUsers and override guard and redirect properties.

protected $redirectTo = 'redirect_path_after_manager_login';

protected function guard()
{
  return Auth::guard('web_manager');
}

The manager model is authenticated and you can get the auuthenticated manager's object Auth::guard('web_manager')->user();

Share:
31,995
RAUSHAN KUMAR
Author by

RAUSHAN KUMAR

A results-driven, customer-focused, articulate and analytical Senior Software Engineer who can think “out of the box”. Strong in design and integration problem-solving skills. Expert in Java, PHP, Node.Js, MySQL with database analysis and design. Skilled in developing business plans, requirements specifications, user documentation, and architectural systems research. Strong written and verbal communications. Interested in a challenging technical track career in an application development environment.

Updated on February 01, 2020

Comments

  • RAUSHAN KUMAR
    RAUSHAN KUMAR over 4 years

    As I know Auth::attempt is used to authenticate users from users table, but i want to authenticate another users from managers table and admin from admins table. I know there are laravel-multiauth plugin already exist. But can we create our own AuthServiceProvider for authenticating users from multiple tables..?