Wednesday, September 27, 2017

Authenticate users from more than two tables in laravel 5

Leave a Comment

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..?

6 Answers

Answers 1

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

Answers 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.

Answers 3

Implement Multi Auth in Larvel 5.2

I'm considering two tables admin and users

Laravel 5.2 has a new artisan command.

php artisan make:auth 

it will generate basic login/register route, view and controller for user table.

Make a admin table as users table for simplicity.

Controller For Admin

app/Http/Controllers/AdminAuth/AuthController app/Http/Controllers/AdminAuth/PasswordController 

(note: I just copied these files from app/Http/Controllers/Auth/AuthController here)

config/auth.php

//Authenticating guards 'guards' => [     'user' =>[         'driver' => 'session',         'provider' => 'user',     ],     'admin' => [         'driver' => 'session',         'provider' => 'admin',     ], ],    //User Providers 'providers' => [     'user' => [         'driver' => 'eloquent',         'model' => App\User::class,     ],     'admin' => [         'driver' => 'eloquent',         'model' => App\Admin::class,     ] ],    //Resetting Password   'passwords' => [     'clients' => [         'provider' => 'client',         'email' => 'auth.emails.password',         'table' => 'password_resets',         'expire' => 60,     ],     'admins' => [         'provider' => 'admin',         'email' => 'auth.emails.password',         'table' => 'password_resets',         'expire' => 60,     ], ], 

route.php

Route::group(['middleware' => ['web']], function () {     //Login Routes...     Route::get('/admin/login','AdminAuth\AuthController@showLoginForm');     Route::post('/admin/login','AdminAuth\AuthController@login');     Route::get('/admin/logout','AdminAuth\AuthController@logout');      // Registration Routes...     Route::get('admin/register', 'AdminAuth\AuthController@showRegistrationForm');     Route::post('admin/register', 'AdminAuth\AuthController@register');      Route::get('/admin', 'AdminController@index');  });   

AdminAuth/AuthController.php

Add two methods and specify $redirectTo and $guard

protected $redirectTo = '/admin'; protected $guard = 'admin'; public function showLoginForm() {     if (view()->exists('auth.authenticate')) {         return view('auth.authenticate');     }          return view('admin.auth.login');     }      public function showRegistrationForm()     {            return view('admin.auth.register');     }   

it will help you to open another login form for admin

creating a middleware for admin

class RedirectIfNotAdmin {     /**      * 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 = 'admin')     {         if (!Auth::guard($guard)->check()) {             return redirect('/');         }          return $next($request);     } } 

register middleware in kernel.php

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

use this middleware in AdminController e.g.,

namespace App\Http\Controllers;  use Illuminate\Http\Request;  use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth;  class AdminController extends Controller {     public function __construct(){         $this->middleware('admin');    }     public function index(){         return view('admin.dashboard');     } } 

That's all needed to make it working and also to get json of authenticated admin use

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

We can access authenticated user directly using

Auth::user() but if you have two authentication table then you have to use

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

for logout

Auth::guard('guard_name')->user()->logout() 

for authenticated user json

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

Hope this helps.

Answers 4

I just done this in my project for two tables namely users and admin but you can do the same for more than two table.
Let's have a look

How to create our own AuthServiceProvider for authenticating users from multiple tables

I have two table admin and users

first of create basic login/register route, view and controller for user table by using Laravel 5.2 artisan command.

php artisan make:auth

Lets make a admin table as users table.

Controller For Admin Part
app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController
(Just copied these files from app/Http/Controllers/Auth/AuthController here)

config/auth.php

//Authenticating guards 'guards' => [     'user' =>[         'driver' => 'session',         'provider' => 'user',     ],     'admin' => [         'driver' => 'session',         'provider' => 'admin',     ], ],    //User Providers 'providers' => [     'user' => [         'driver' => 'eloquent',         'model' => App\User::class,     ],     'admin' => [         'driver' => 'eloquent',         'model' => App\Admin::class,     ] ],    //Resetting Password   'passwords' => [     'clients' => [         'provider' => 'client',         'email' => 'auth.emails.password',         'table' => 'password_resets',         'expire' => 60,     ],     'admins' => [         'provider' => 'admin',         'email' => 'auth.emails.password',         'table' => 'password_resets',         'expire' => 60,     ], ],   

route.php

Route::group(['middleware' => ['web']], function () {     //Login Routes...     Route::get('/admin/login','AdminAuth\AuthController@loginPage');     Route::post('/admin/login','AdminAuth\AuthController@login');     Route::get('/admin/logout','AdminAuth\AuthController@logout');      // Registration Routes...     Route::get('admin/register', 'AdminAuth\AuthController@registrationPage');     Route::post('admin/register', 'AdminAuth\AuthController@register');      Route::get('/admin', 'AdminController@index');  });   

AdminAuth/AuthController.php

Add two methods and specify $redirectTo and $guard

protected $redirectTo = '/admin'; protected $guard = 'admin'; public function loginPage() {     if (view()->exists('auth.authenticate')) {         return view('auth.authenticate');     }      return view('admin.auth.login'); } public function registrationPage() {     return view('admin.auth.register'); }   

it will help you to open another login form for admin

creating a middleware for admin

class RedirectIfNotAdmin { /**  * 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 = 'admin') {     if (!Auth::guard($guard)->check()) {         return redirect('/');     }      return $next($request); } 

}

register middleware in kernel.php

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

use this middleware in AdminController e.g.,

namespace App\Http\Controllers;  use Illuminate\Http\Request;  use App\Http\Requests; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth;  class AdminController extends Controller {     public function __construct(){         $this->middleware('admin');    } public function index(){         return view('admin.dashboard');     } } 

Authentication
We can access authenticated user directly using
Auth::user() but if you have two authentication table then you have to use

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

Like
Auth::guard('admin')->user()

And also for reference check this https://laracasts.com/discuss/channels/laravel/52-auth-multiple-tables?page=1

Answers 5

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

Uthenticate 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';     } 

Answers 6

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

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment