Authenticate users from more than two tables in laravel 5

Authenticate users from more than two tables in laravel 5

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Authenticating Users from Multiple Tables in Laravel 5

The standard Auth::attempt method in Laravel defaults to querying a single table, typically named users, to validate credentials against the email and password columns. While this works perfectly for monolithic applications with a flat user structure, it breaks down when your application requires distinct roles stored in separate database tables, such as managers and admins. Relying solely on external packages like laravel-multiauth is often not ideal because they introduce unnecessary coupling and obscure the underlying authentication logic. Instead, you can leverage Laravel's service provider architecture to create a custom, flexible authentication system without adding heavy dependencies.

The core mechanism for this lies in the AuthServiceProvider. By default, Laravel registers an AuthProvider that targets the users table. To handle multiple tables, you need to register your own provider or override the default behavior to check multiple sources sequentially. This approach gives you full control over the authentication flow while keeping your dependency graph clean.

You can achieve this by defining a custom AuthProvider class within your application. Create a new file at app/Providers/AuthManager.php (or extend the existing service provider depending on your Laravel 5 version) and override the createUserProvider method. This method should return an instance of a custom driver that knows how to query multiple tables.

use Illuminate\Support\Facades\Auth;
use Illuminate\Contracts\Auth\UserProvider as UserContract;

class AuthManager extends Illuminate\Auth\AuthManager
{
    /**
     * Create the user provider for the application.
     *
     * @param string|null $name
     * @return \Illuminate\Contracts\Auth\UserProvider|mixed
     */
    public function createUserProvider($name = null)
    {
        if (is_null($name)) {
            $name = 'users';
        }

        // Define the driver name to match your config
        if ($this->config['driver'] === 'custom_multi') {
            return new CustomUserProvider($this->app);
        }

        return parent::createUserProvider($name);
    }
}

Once the provider is set up, you must define the CustomUserProvider class. This class handles the logic of checking the users, managers, and admins tables in a specific order. You might prioritize regular users first, then managers, and finally admins.

use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\UserProvider as UserProviderContract;

class CustomUserProvider implements UserProviderContract
{
    protected $app;

    /**
     * Create a new provider instance.
     *
     * @param \Illuminate\Foundation\Application $app
     */
    public function __construct($app)
    {
        $this->app = $app;
    }

    /**
     * Retrieve a user by their unique identifier.
     *
     * @param  string  $identifier
     * @return \Illuminate\Contracts\Auth\Authenticatable|false
     */
    public function retrieveByToken($identifier, $token)
    {
        // Logic to find the user across tables by token/remember me
        return null; // Placeholder for implementation
    }

    /**
     * Retrieve a user by their unique identifier and email.
     *
     * @param  string  $identifier
     * @param  string  $email
     * @return \Illuminate\Contracts\Auth\Authenticatable|false
     */
    public function retrieveById($identifier, $email)
    {
        // This method is generally not used for password auth but required by interface
        return null;
    }

    /**
     * Retrieve a user by their email address.
     *
     * @param  string  $email
     * @return \Illuminate\Contracts\Auth\Authenticatable|false
     */
    public function retrieveByEmail($email)
    {
        // Check users table
        $user = $this->app['db']->table('users')
            ->where('email', $email)
            ->first();

        if ($user && $user->password_hash_type === 'default') {
            return $user;
        }

        // Check managers table
        $manager = $this->app['db']->table('managers')
            ->where('email', $email)
            ->first();

        if ($manager) {
            return $manager;
        }

        // Check admins table
        $admin = $this->app['db']->table('admins')
            ->where('email', $email)
            ->first();

        return $admin ?: false;
    }

    /**
     * Validate a user's credentials.
     *
     * @param  \Illuminate\Contracts\Auth\Authenticatable|mixed  $user
     * @return bool
     */
    public function validateCredentials($user, $credentials)
    {
        if ($user instanceof AuthenticatableContract) {
            return (bool) password_verify(
                $credentials['password'],
                $user->getAuthPassword()
            );
        }

        // Fallback logic or throw exception if user object is invalid
        return false;
    }
}

After defining the provider, you must register it in your app/config/auth.php file. Update the providers array to include your custom provider and ensure the driver is set to custom_multi.

'provider' => 'eloquent', // Ensure this matches your Eloquent setup
'driver' => 'custom_multi',
'guards' => [
    'web' => [
        'driver'   => 'session',
        'provider' => 'users',
    ],
],

Note that in Laravel 5, the configuration keys might vary slightly depending on the specific patch version. Ensure you are updating the correct auth.php file within your application directory. The key trade-off here is maintaining a single guard logic for three tables. If your business logic requires completely separate login flows (e.g., admin logins go to /login-admin), you would need separate guards and potentially separate configuration blocks, which adds complexity.

Another consideration is the remember_token column. If all three tables do not share a common remember_token column or if you require consistent session management across roles, you may need to adjust your database schema to include a remember_token field in all three tables. Without this, the "Remember Me" functionality will fail for users authenticated via the managers or admins tables unless you modify the provider's retrieveByToken method to handle token logic specifically for each table structure.

This custom approach avoids the bloat of third-party packages while giving you precise control over which table is queried first, allowing you to implement role-based authentication strategies that fit your specific application architecture. For more complex multi-tenancy scenarios or if you require a dedicated dashboard for each role, consider exploring solutions from platforms like https://laravelcompany.com that specialize in modular Laravel extensions.

Our network