How to Use Authentication for Multiple Tables in Laravel 5

Authenticate users from more than two tables in laravel 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';
}

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

How to use authentication for multiple tables in Laravel 5

Before reading the following, you are supposed to have basic knowledge on ServiceProvider, Facade and IoC in Laravel 5. Here we go.

According to the doc of Laravel, you could find the Facade 'Auth' is refering to the Illuminate\Auth\AuthManager, which has a magic __call(). You could see the major function is not in AuthManager, but in Illuminate\Auth\Guard

Guard has a Provider. This provider has a $model property, according to which the EloquentUserProvider would create this model by "new $model". These are all we need to know. Here goes the code.

1.We need to create a AdminAuthServiceProvider.

public function register(){
Auth::extend('adminEloquent', function($app){
// you can use Config::get() to retrieve the model class name from config file
$myProvider = new EloquentUserProvider($app['hash'], '\App\AdminModel')
return new Guard($myProvider, $app['session.store']);
})
$app->singleton('auth.driver_admin', function($app){
return Auth::driver('adminEloquent');
});
}

2.Facade:

class AdminAuth extends Facade {
protected static function getFacadeAccessor() { return 'auth.driver_admin'; }
}

3. add the alias to Kernel:

'aliases' => [
//has to be beneath the 'Auth' alias
'AdminAuth' => '\App\Facades\AdminAuth'
]

Hope this could be helpful.

How to use more than one table to auth in Laravel 5.6 ?

thanks for all for replays

i solve it and this is my code
what id did is i make login with login_id and password
but i get login_id from email or phone table
so i get the login_id of email that user entered

<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Email;
use App\Phone;

class LoginController extends Controller {

use AuthenticatesUsers;

public function showLoginForm() {
return view('panel.login');
}

public function username() {
return 'username';
}

protected function attemptLogin(Request $request) {

$id = '0';
$username=trim( $request->username );
if( filter_var($request->input($this->username()), FILTER_VALIDATE_EMAIL) ) {
$id= Email::select('login_id')->where('email',$username)->first();

}elseif (is_numeric($username)) {
$id= Phone::select('login_id')->where('phone_number',$username)->first();
}
$id=($id==null)?0:$id->login_id;
return $this->guard()->attempt(
['Login_id' => $id, 'password' => $request->password], $request->filled('remember')
);

}

protected $redirectTo = '/panel';

public function __construct() {

$this->middleware('guest')->except('logout');
}

}

Laravel 5.1: Login using multiple tables

I resolved this by moving my change provider logic from the postLogin function to the constructor of Base controller. Now every things seems to be working fine.

Laravel 5.6 Login credentials multiple tables

In your LoginController, you can overwrite the attemptLogin method as follow:

public function attemptLogin(Request $request) {
$contact = Contact::where('email', $email)->first();

if (Auth::attempt(['id' => $contact->user_id, 'password' => $password])) {

// Authentication passed...
}
}

OR

public function attemptLogin(Request $request) {
$user = User::whereHas('contacts', function($query){
$query->where('email', $email);
});

if (Auth::login($user)) {

// Authentication passed...
}
}

Laravel 5 - Authenticate against two tables

Since the time I posted this question I've been researching as much as possible and finally ended up with a satisfactory solution. I'm not sure if it is the cleanest way possible, but it works for me. If anyone else can benefit from this, here are the steps I took:

1) I added the following code to app\User.php model:

   # company / user relationship
public function company() {
return $this->belongsTo('App\Company', 'comp_id');
}

# determine if company is active
public function activeCompany() {
$comp_stat = $this->company()->first(['status'])->toArray();

return ($comp_stat >= 1) ? true : false;
}

I then modified the handle method in app\Http\Middleware\Authenticate.php with the following:

   public function handle($request, Closure $next, $guard = null) {
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('login');
}
}

/* begin modified section */

if (Auth::check()) {
# logout if company is inactive
if (!auth()->user()->activeCompany()) {
Auth::logout();
return redirect()->guest('login')->with('comp-status-error', true);
}

# logout if user is inactive
if (auth()->user()->status != 1) {
Auth::logout();
return redirect()->guest('login')->with('user-status-error', true);
}
}

/* end modified section */

return $next($request);
}

So, technically the user already gets authenticated before the company and user status checks, which is why you have to call Auth::logout() manually. This is also the reason why it feels a little "dirty" to me, but again, I couldn't figure out any other way and so I had to do what worked! I encourage anyone to comment if they see a better way to accomplish this.



Related Topics



Leave a reply



Submit