Extend Third-Party Models While Keeping Laravel Auth

πŸ“– 2 minutes read

When you need to extend a third-party Eloquent model instead of Laravel’s default base classes, you might lose Laravel’s built-in authentication functionality. Here’s how to preserve it.

The Problem

Say you’re integrating a package that provides its own Eloquent models β€” maybe you’re connecting to an external database or using a library like Corcel to query WordPress data directly. You want your User model to extend the package’s base model, but Laravel’s authentication expects specific contracts and traits.

The Solution: Manual Implementation

Laravel’s Authenticatable class (the default base for User models) is just a convenient wrapper. Under the hood, it implements three contracts and uses four traits. You can apply these yourself:

use Vendor\Package\Model as ThirdPartyModel;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\MustVerifyEmail;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Foundation\Auth\Access\Authorizable;

class User extends ThirdPartyModel implements
    AuthenticatableContract,
    AuthorizableContract,
    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword, MustVerifyEmail;
    use HasFactory, Notifiable; // Your existing traits
}

What Each Part Does

  • Authenticatable: Login/logout, remember tokens, password verification
  • Authorizable: Gate and policy authorization
  • CanResetPassword: Password reset emails and tokens
  • MustVerifyEmail: Email verification (optional)

Check for Conflicts First

Before applying all four traits, check if the third-party model already implements some of them. For example, if the package model already has Authenticatable, you’d skip that trait to avoid conflicts.

You can inspect the package’s base model source or test by adding traits one at a time and watching for “trait method conflict” errors.

Why This Works

Laravel’s auth system doesn’t care about inheritance β€” it only checks for contract implementation. As long as your model implements AuthenticatableContract and the required methods (via traits or manual implementation), Auth::user(), middleware, and guards will work normally.

This pattern lets you integrate any Eloquent-compatible package while keeping Laravel’s authentication intact.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *