PHPackages                             nadun24/laravel-hybrid-auth - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. nadun24/laravel-hybrid-auth

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

nadun24/laravel-hybrid-auth
===========================

Redis-first, database-fallback authentication system for Laravel with Sanctum-compatible API

v1.0.2(5mo ago)02MITPHPPHP ^8.2|^8.3CI failing

Since Dec 13Pushed 5mo agoCompare

[ Source](https://github.com/Nadun24/laravel-hybrid-auth)[ Packagist](https://packagist.org/packages/nadun24/laravel-hybrid-auth)[ RSS](/packages/nadun24-laravel-hybrid-auth/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (7)Versions (4)Used By (0)

Laravel Hybrid Auth
===================

[](#laravel-hybrid-auth)

A high-performance Redis-first, database-fallback authentication system for Laravel with a Sanctum-compatible API. This package provides lightning-fast token validation using Redis while maintaining reliability through automatic database fallback when Redis is unavailable.

Features
--------

[](#features)

- 🚀 **Redis-First Performance**: Token validation in microseconds using Redis
- 💾 **Automatic DB Fallback**: Seamless fallback to database when Redis is down
- 🔄 **Sanctum-Compatible API**: Drop-in replacement for Laravel Sanctum
- 🎯 **Token Abilities**: Fine-grained permissions for API tokens
- ⚡ **Automatic Sync**: Database tokens automatically sync to Redis
- 🔒 **Secure**: SHA-256 hashed tokens with configurable expiration
- 📊 **Health Monitoring**: Built-in Redis health checks with caching
- 🎨 **Zero Configuration**: Works out of the box with sensible defaults

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Laravel 10.x or 11.x
- Redis server (optional but recommended)
- MySQL/PostgreSQL/SQLite

Installation
------------

[](#installation)

### 1. Install via Composer

[](#1-install-via-composer)

```
composer require Nadun24/laravel-hybrid-auth
```

### 2. Publish Configuration and Migrations

[](#2-publish-configuration-and-migrations)

```
php artisan vendor:publish --tag=hybrid-auth-config
php artisan vendor:publish --tag=hybrid-auth-migrations
```

### 3. Run Migrations

[](#3-run-migrations)

```
php artisan migrate
```

### 4. Configure Authentication Guard

[](#4-configure-authentication-guard)

In `config/auth.php`, add the hybrid-token guard:

```
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'hybrid-token',
        'provider' => 'users',
    ],
],
```

### 5. Add Trait to User Model

[](#5-add-trait-to-user-model)

Add the `HasApiTokens` trait to your User model:

```
use Nadun24\LaravelHybridAuth\Traits\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;

    // ... rest of your model
}
```

Configuration
-------------

[](#configuration)

The configuration file is located at `config/hybrid-auth.php`:

```
return [
    // Redis connection settings
    'redis' => [
        'connection' => env('HYBRID_AUTH_REDIS_CONNECTION', 'default'),
        'prefix' => env('HYBRID_AUTH_REDIS_PREFIX', 'hybrid_auth'),
    ],

    // Database settings
    'database' => [
        'connection' => env('HYBRID_AUTH_DB_CONNECTION', null),
        'table' => 'personal_access_tokens',
    ],

    // Token expiration in minutes (null = never expires)
    'expiration' => env('HYBRID_AUTH_EXPIRATION', null),

    // Optional token prefix
    'token_prefix' => env('HYBRID_AUTH_TOKEN_PREFIX', ''),

    // Redis health check settings
    'redis_timeout' => env('HYBRID_AUTH_REDIS_TIMEOUT', 0.1),
    'redis_retry_after' => env('HYBRID_AUTH_REDIS_RETRY_AFTER', 60),
    'cache_redis_status' => env('HYBRID_AUTH_CACHE_REDIS_STATUS', true),

    // Enable/disable token abilities
    'abilities_enabled' => env('HYBRID_AUTH_ABILITIES_ENABLED', true),
];
```

Usage
-----

[](#usage)

### Creating Tokens

[](#creating-tokens)

#### Basic Token Creation

[](#basic-token-creation)

```
$user = User::find(1);

// Create a token with all abilities
$token = $user->createToken('mobile-app');

// Access the plain text token (only available once)
$plainTextToken = $token->plainTextToken;

// Return to user
return response()->json([
    'token' => $plainTextToken,
    'type' => 'Bearer'
]);
```

#### Token with Specific Abilities

[](#token-with-specific-abilities)

```
$token = $user->createToken('admin-token', ['create', 'update', 'delete']);
```

#### Token with Expiration

[](#token-with-expiration)

```
$expiresAt = now()->addDays(30);
$token = $user->createToken('temp-token', ['*'], $expiresAt);
```

### Authenticating Requests

[](#authenticating-requests)

#### Protect Routes

[](#protect-routes)

In `routes/api.php`:

```
use Illuminate\Support\Facades\Route;

Route::middleware('auth:api')->group(function () {
    Route::get('/user', function (Request $request) {
        return $request->user();
    });

    Route::post('/posts', [PostController::class, 'store']);
});
```

#### Making Authenticated Requests

[](#making-authenticated-requests)

Include the token in the Authorization header:

```
curl -H "Authorization: Bearer YOUR_TOKEN_HERE" \
     https://your-app.com/api/user
```

Or as a query parameter:

```
curl https://your-app.com/api/user?access_token=YOUR_TOKEN_HERE
```

### Checking Token Abilities

[](#checking-token-abilities)

#### In Controllers

[](#in-controllers)

```
public function store(Request $request)
{
    if ($request->user()->tokenCan('create')) {
        // User has 'create' ability
        return Post::create($request->all());
    }

    return response()->json(['message' => 'Forbidden'], 403);
}
```

#### Using Middleware

[](#using-middleware)

Register middleware in `app/Http/Kernel.php`:

```
protected $middlewareAliases = [
    // ... other middleware
    'abilities' => \Nadun24\LaravelHybridAuth\Middleware\CheckAbilities::class,
    'ability' => \Nadun24\LaravelHybridAuth\Middleware\CheckForAnyAbility::class,
];
```

Protect routes with required abilities:

```
// User must have ALL specified abilities
Route::post('/admin/users', [UserController::class, 'store'])
    ->middleware(['auth:api', 'abilities:create,update']);

// User must have ANY of the specified abilities
Route::get('/reports', [ReportController::class, 'index'])
    ->middleware(['auth:api', 'ability:view-reports,view-analytics']);
```

### Managing Tokens

[](#managing-tokens)

#### Get User's Tokens

[](#get-users-tokens)

```
$tokens = $user->tokens;

foreach ($tokens as $token) {
    echo $token->name;
    echo $token->last_used_at;
}
```

#### Revoke Current Token

[](#revoke-current-token)

```
// In a controller
public function logout(Request $request)
{
    $request->user()->revokeCurrentToken();

    return response()->json(['message' => 'Logged out successfully']);
}
```

#### Revoke All Tokens

[](#revoke-all-tokens)

```
$user->revokeAllTokens();
```

#### Delete Specific Token

[](#delete-specific-token)

```
$user->tokens()->where('name', 'mobile-app')->delete();
```

How It Works
------------

[](#how-it-works)

### Token Creation Flow

[](#token-creation-flow)

1. Plain text token is generated
2. Token is hashed using SHA-256
3. Token is stored in Redis (if available)
4. Token is stored in database (always)
5. Plain text token is returned to user (only once)

### Token Validation Flow

[](#token-validation-flow)

1. Request arrives with token
2. Token is hashed
3. **Redis Check**: Hash is looked up in Redis (microsecond latency)
    - If found: User is authenticated immediately
    - If not found or Redis down: Continue to step 4
4. **Database Fallback**: Hash is looked up in database
    - If found: User is authenticated and token is synced to Redis
    - If not found: Authentication fails

### Redis Health Monitoring

[](#redis-health-monitoring)

- Automatic Redis connection health checks
- Failed connections are cached to prevent repeated failures
- Configurable retry intervals
- Transparent fallback to database

Performance Benefits
--------------------

[](#performance-benefits)

### With Redis Available

[](#with-redis-available)

- **Token Validation**: &lt; 1ms (vs 10-50ms database query)
- **Concurrent Requests**: Handles 10,000+ req/sec per server
- **Database Load**: Reduced by 90%+

### With Redis Down

[](#with-redis-down)

- **Automatic Fallback**: Zero downtime
- **Transparent Operation**: No code changes needed
- **Database Validation**: Standard Laravel performance

Testing
-------

[](#testing)

Run the test suite:

```
composer test
```

Run with coverage:

```
composer test:coverage
```

Best Practices
--------------

[](#best-practices)

### 1. Token Security

[](#1-token-security)

```
// ✅ Good: Store tokens securely on client
localStorage.setItem('api_token', token);

// ❌ Bad: Never expose tokens in URLs permanently
https://app.com/dashboard?token=xyz  // Avoid this
```

### 2. Token Abilities

[](#2-token-abilities)

```
// ✅ Good: Use specific abilities
$token = $user->createToken('mobile', ['read', 'write']);

// ❌ Bad: Don't give all abilities unless necessary
$token = $user->createToken('mobile', ['*']);  // Use sparingly
```

### 3. Token Expiration

[](#3-token-expiration)

```
// ✅ Good: Set expiration for sensitive operations
$token = $user->createToken('payment', ['payment'], now()->addHours(1));

// ✅ Good: Long-lived tokens for mobile apps
$token = $user->createToken('mobile', ['*'], now()->addYear());
```

### 4. Redis Configuration

[](#4-redis-configuration)

```
# Recommended production settings
HYBRID_AUTH_REDIS_CONNECTION=cache
HYBRID_AUTH_REDIS_PREFIX=auth
HYBRID_AUTH_REDIS_TIMEOUT=0.1
HYBRID_AUTH_REDIS_RETRY_AFTER=60
HYBRID_AUTH_CACHE_REDIS_STATUS=true
```

Troubleshooting
---------------

[](#troubleshooting)

### Redis Connection Issues

[](#redis-connection-issues)

If you see warnings about Redis connections:

1. Check Redis is running: `redis-cli ping`
2. Verify connection settings in `.env`
3. Check firewall rules
4. Review `config/database.php` Redis configuration

The package will automatically fall back to database validation.

### Token Not Working

[](#token-not-working)

1. Ensure token is sent in correct format: `Bearer TOKEN`
2. Check token hasn't expired
3. Verify guard is set to `api` in routes
4. Check user model has `HasApiTokens` trait

### Performance Issues

[](#performance-issues)

1. Enable Redis for best performance
2. Set appropriate `redis_retry_after` value
3. Enable `cache_redis_status` to reduce connection checks
4. Add database indexes on `personal_access_tokens.token`

Migration from Sanctum
----------------------

[](#migration-from-sanctum)

This package is designed as a drop-in replacement for Laravel Sanctum:

1. Install this package
2. Replace `Laravel\Sanctum\HasApiTokens` with `Nadun24\LaravelHybridAuth\Traits\HasApiTokens`
3. Update guard from `sanctum` to `hybrid-token` in `config/auth.php`
4. Update middleware from `auth:sanctum` to `auth:api`

Your existing token creation and validation code should work without changes!

Contributing
------------

[](#contributing)

Contributions are welcome! Please submit pull requests or issues on GitHub.

License
-------

[](#license)

This package is open-sourced software licensed under the MIT license.

Credits
-------

[](#credits)

Inspired by Laravel Sanctum and built to provide enhanced performance through Redis caching while maintaining reliability.

Support
-------

[](#support)

For issues, questions, or contributions, please visit the GitHub repository.

###  Health Score

35

—

LowBetter than 79% of packages

Maintenance73

Regular maintenance activity

Popularity2

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

151d ago

PHP version history (2 changes)v1.0.0PHP ^8.1|^8.2|^8.3

v1.0.1PHP ^8.2|^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/2e6869b3113e9b506304111d9d3d868bbd94d1519c481a5b4bce6d674f58c347?d=identicon)[Nadun24](/maintainers/Nadun24)

---

Top Contributors

[![Nadun24](https://avatars.githubusercontent.com/u/96878904?v=4)](https://github.com/Nadun24 "Nadun24 (3 commits)")

---

Tags

apilaravelAuthenticationtokenredissanctum

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/nadun24-laravel-hybrid-auth/health.svg)

```
[![Health](https://phpackages.com/badges/nadun24-laravel-hybrid-auth/health.svg)](https://phpackages.com/packages/nadun24-laravel-hybrid-auth)
```

###  Alternatives

[tymon/jwt-auth

JSON Web Token Authentication for Laravel and Lumen

11.5k49.1M350](/packages/tymon-jwt-auth)[hasinhayder/tyro

Tyro - The ultimate Authentication, Authorization, and Role &amp; Privilege Management solution for Laravel 12 &amp; 13

6712.1k2](/packages/hasinhayder-tyro)[alajusticia/laravel-logins

Session management in Laravel apps, user notifications on new access, support for multiple separate remember tokens, IP geolocation, User-Agent parser

2011.0k](/packages/alajusticia-laravel-logins)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
