Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Auth Laravel Package

delight-im/auth

delight-im/auth is a framework-agnostic PHP authentication library with a simple API. It handles registration, login, email verification, password resets, sessions, cookies, roles, and social login, with no complex setup required.

View on GitHub
Deep Wiki
Context7

Getting Started

  • Read the README examples first, then inspect src/Auth.php, src/Database.php, and the SQL schema files under database/ (mysql.sql, pgsql.sql, sqlite.sql). Almost everything you need is on Delight\Auth\Auth.
  • Install with composer require delight-im/auth.
  • Create the PHP-Auth tables before using it. There are no Laravel migrations, facades, or config files. Either run the supplied SQL in a separate schema/database, or copy it into a Laravel migration and rename tables to match a prefix.
  • Bind Delight\Auth\Auth as a singleton, but resolve it lazily. Do not instantiate it in a global bootstrapper before Laravel’s session middleware has run.
// app/Providers/PhpAuthServiceProvider.php
use Delight\Auth\Auth;
use Illuminate\Support\ServiceProvider;

public function register(): void
{
    $this->app->singleton(Auth::class, function ($app) {
        return new Auth($app['db']->connection()->getPdo(), [
            'db_table_prefix' => 'php_auth_',
            'session_name'    => 'php_auth_session',
            'cookie_name'     => 'php_auth_remember',
            'throttling'      => true,
        ]);
    });
}
  • First use case: a login controller. Validate input, call $auth->login($email, $password, $remember), catch the package’s specific exceptions, then redirect. Protect routes with middleware that checks $auth->isLoggedIn().
try {
    $auth->login($request->email, $request->password, $request->boolean('remember'));
    return redirect()->intended('/dashboard');
} catch (\Delight\Auth\InvalidEmailException|\Delight\Auth\InvalidPasswordException $e) {
    return back()->withErrors(['email' => 'Invalid credentials.']);
} catch (\Delight\Auth\EmailNotVerifiedException $e) {
    return back()->withErrors(['email' => 'Please verify your email address.']);
} catch (\Delight\Auth\TooManyRequestsException $e) {
    return back()->withErrors(['email' => 'Too many attempts. Try again later.']);
}

Implementation Patterns

  • Service-provider singleton. Inject Delight\Auth\Auth into controllers and middleware. Keep the PDO source explicit via DB::connection()->getPdo() or a dedicated connection if you want isolation.
  • One controller per flow. Registration, login, logout, email confirmation, forgot-password, reset-password, change-password, and change-email each map cleanly to a small controller action using Form Requests for validation.
  • Email verification callback. register() accepts a callback receiving $selector and $token. Build a Laravel route URL there and queue a Mailable. Do not send mail synchronously inside the callback.
$userId = $auth->register($email, $password, $username, function ($selector, $token) use ($email) {
    $url = route('auth.verify', ['selector' => $selector, 'token' => $token]);
    Mail::to($email)->queue(new VerifyEmail($url));
});
  • Password reset flow. Use $auth->forgotPassword($email, $callback) to generate the reset selector/token, then $auth->resetPassword($selector, $token, $newPassword) in the reset action. Catch InvalidSelectorTokenPairException and TokenExpiredException.
  • Middleware and view data. PHP-Auth does not populate Laravel’s auth()->user(). If you keep it as the source of truth, share a small DTO with views from middleware or a view composer:
View::share('authUser', $auth->isLoggedIn() ? [
    'id'    => $auth->getUserId(),
    'email' => $auth->getEmail(),
] : null);
  • Bridge to Laravel auth only if necessary. If you want Laravel guards, policies, and auth()->user(), use PHP-Auth for credential verification and token flows, then bridge on successful login. This only works cleanly if you have a compatible Eloquent user model or sync records. Clear PHP-Auth’s session afterward if you do not want dual sessions.
$auth->login($email, $password, $remember);
$id = $auth->getUserId();
$auth->logout(); // clear PHP-Auth session/cookie after bridging
LaravelAuth::loginUsingId($id);
  • Roles. Use PHP-Auth’s admin helpers for lightweight roles: $auth->admin()->createRole('admin'), addRoleForUserById(), doesUserHaveRole(), and $auth->hasRole('admin') for the current user. Treat this as a bitmask role flag, not a full RBAC system; map to Laravel Gate/policies if you bridge.
  • Testing. Use SQLite :memory: in tests, run the PHP-Auth SQLite schema in setUp(), and bind Delight\Auth\Auth to the test PDO. Assert the package exceptions directly rather than only asserting HTTP responses.
  • API/SPA use. PHP-Auth is session/cookie-based. It does not issue bearer tokens or JWTs. For Laravel APIs, prefer Sanctum or Fortify unless you are deliberately adding a token layer around PHP-Auth’s credential checks.

Gotchas and Tips

  • Not a Laravel package. No facade, config publish, migrations, guard, or Blade components. You own the integration code.
  • Session and cookie collisions are the main risk. PHP-Auth expects to own its session and remember-me cookie. Set distinct session_name and cookie_name values. If Laravel’s StartSession middleware has already started the native session, PHP-Auth’s session handling can conflict. Resolve it only inside auth routes/controllers, or test a bridging pattern carefully.
  • Do not reuse Laravel’s users table. PHP-Auth expects columns such as verified, roles_mask, status, registered, and last_login, which do not match Laravel’s default schema. Use a prefixed table set or a separate database.
  • Table prefixes must match the SQL. db_table_prefix changes runtime queries, but the SQL schema you run must create tables with the same names. Copy and edit the supplied SQL rather than assuming the package migrates for you.
  • Exceptions are control flow. Catch specific exceptions such as InvalidEmailException, InvalidPasswordException, UserAlreadyExistsException, EmailNotVerifiedException, TooManyRequestsException, InvalidSelectorTokenPairException, and TokenExpiredException. Avoid a blanket catch (\Exception) that hides throttling and verification failures.
  • Wire email yourself. The registration and password-reset callbacks are where you send mail. Use Laravel Mail with queues, correct app URLs, and token expiration. Avoid logging selector/token pairs.
  • Throttling table growth. Enable throttling, but schedule cleanup of users_throttling. Behind proxies, ensure trusted proxy configuration so IP-based throttling sees the real client IP.
  • Password hashing is compatible but not shared state. PHP-Auth uses password_hash, so hashes are generally compatible with Laravel’s Hash, but do not double-hash or migrate hashes casually. If you bridge, verify Laravel’s user provider is reading the same password column.
  • CSRF is not included. Put auth routes behind Laravel’s web middleware and VerifyCsrfToken. PHP-Auth handles authentication, not CSRF protection.
  • Cookie flags matter. Set cookie_secure, cookie_same_site, session_cookie_secure, and sensible lifetimes in production. Remember-me cookies are long-lived.
  • Roles are limited. PHP-Auth roles are bitmask-based and suited to simple admin/user distinctions. They are not a replacement for Laravel’s authorization layer.
  • Debugging checklist. Inspect the PHP-Auth tables directly, check $_SESSION keys and cookie names, confirm the PDO driver matches the SQL dialect, and verify the table prefix. Most “login silently fails” issues are session/cookie collisions or schema mismatches.
  • Evaluate alternatives for greenfield Laravel. For a new Laravel app, Breeze, Fortify, or Sanctum will usually be less friction. PHP-Auth is most useful when you want a small, framework-agnostic auth layer, a legacy sidecar, or its ready-made verification and throttling flows without adopting Laravel’s auth stack.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jinas/dhivatar
store-doc/laravel-storage-driver
plus-it/laravel-translation-manager
diephp/perhaps
diephp/telegraph
osmaviation/spreadsheet
microsoft/fluentui-system-icons
mmccook/php-json-canonicalization-scheme
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console
pnscripts/filament-broadquill-lite
pnscripts/laravel-sentfold-lite
vleap/mx-sdk-laravel-internal
twidpay/utils
htetmyathlaing/scout-elasticsearch-driver
artisan-toolbox/front-awesome
ls/client-assistant
users-au/laravel-client
cgv/localized-resource