upnorthal
1317
8
Laravel

5.2 - Auth - Multiple Tables

Posted 3 years ago by upnorthal

Given version 5.2 now supports multiple auth tables, I though I would give this a go.

I have created an additional table called person.

I've modified auth.php, but adding a new persons source.

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

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],

         'persons' => [
             'driver' => 'eloquent',
             'model' => 'App\Person::class',
         ],

I have created new routes and controllers for my persons table (I've also created some new views)

Route::group(['middleware' => ['web']], function () {

    // Authentication routes...
    Route::get('personauth/login', 'PersonAuth\PersonAuthController@getLogin');
    Route::post('personauth/login', 'PersonAuth\PersonAuthController@postLogin');
    Route::get('personauth/logout', 'PersonAuth\PersonAuthController@getLogout');

    // Registration routes...
    Route::get('personauth/register', 'PersonAuth\PersonAuthController@getRegister');
    Route::post('personauth/register', 'PersonAuth\PersonAuthController@postRegister');


});

Within my PersonAuthController, I have added a method to allow new person users to be created (just overriding the same method from the trait RegistersUsers)

(also I've over-ridden the methods that show the login and register view to point to my new templates)

    protected function create(array $data)
    {
        return Person::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
        ]);
    }


    public function showRegistrationForm()
    {
        return view('personauth.register');
    }

   public function showLoginForm()
    {
        if (view()->exists('personauth.authenticate')) {
            return view('personauth.authenticate');
        }

        return view('personauth.login');
    }

I can create new person users fine.

How am I supposed to authenticate against my new person table? Looking in the AuthenticatesUsers trait I don't get what I am supposed to change in the method login ?

I think this is the bit that does the actual auth check

   if (Auth::attempt($credentials, $request->has('remember'))) {
            return $this->handleUserWasAuthenticated($request, $throttles);
        }

How do I tell this to query against my person table?

Please sign in or create an account to participate in this conversation.