PHPackages                             draidel/laravel-supabase-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. draidel/laravel-supabase-auth

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

draidel/laravel-supabase-auth
=============================

Enterprise-grade Laravel package providing complete Supabase authentication integration with advanced security, monitoring, and scalability features

v0.1(9mo ago)923[1 issues](https://github.com/Draidel/laravel-supabase-auth/issues)MITPHPPHP ^8.1

Since Jul 21Pushed 9mo agoCompare

[ Source](https://github.com/Draidel/laravel-supabase-auth)[ Packagist](https://packagist.org/packages/draidel/laravel-supabase-auth)[ Docs](https://github.com/supabase/laravel-auth)[ RSS](/packages/draidel-laravel-supabase-auth/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (15)Versions (3)Used By (0)

Laravel Supabase Auth
=====================

[](#laravel-supabase-auth)

[![Latest Version on Packagist](https://camo.githubusercontent.com/ace16c598665dfeacc6d53af98d1a0cb51ab569a9dd63ccd0e322f86d9315e60/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73757061626173652f6c61726176656c2d617574682e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/supabase/laravel-auth)[![GitHub Tests Action Status](https://camo.githubusercontent.com/66d748f83256d0c14b501c7389a9e5542f5a833efe3f236b0014071c52ed0fc7/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f73757061626173652f6c61726176656c2d617574682f54657374733f6c6162656c3d7465737473)](https://github.com/Draidel/laravel-supabase-auth/actions)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/6b291b42070d20c6eb98296b5ed04f350245cbb118cfc0c6ce96625f087a7e2a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f73757061626173652f6c61726176656c2d617574682f436865636b253230262532306669782532307374796c696e673f6c6162656c3d636f64652532307374796c65)](https://github.com/Draidel/laravel-supabase-auth/actions)[![Total Downloads](https://camo.githubusercontent.com/ad6c78bcd1d2f96ad8c905f80f1f7609bf57989a886631a18d279d3a4cf9ef54/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f73757061626173652f6c61726176656c2d617574682e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/supabase/laravel-auth)

An enterprise-grade Laravel package that completely replaces Laravel's native authentication system with Supabase authentication. Built with production-ready features including circuit breakers, rate limiting, comprehensive caching, monitoring, and advanced security.

✨ Features
----------

[](#-features)

- 🔐 **Complete Auth Replacement**: Drop-in replacement for Laravel's native authentication
- 🏢 **Enterprise-Ready**: Circuit breakers, rate limiting, caching, and monitoring
- 🚀 **High Performance**: Intelligent caching with Redis support and connection pooling
- 🛡️ **Security First**: Advanced password policies, secure cookies, and CSRF protection
- 📊 **Observability**: Comprehensive logging, metrics collection, and health checks
- 🔄 **Resilient**: Automatic retry logic, token refresh, and graceful error handling
- 🎯 **OAuth Support**: Social login with Google, GitHub, Discord, and more
- 📧 **Email Features**: Verification, password reset, and magic links
- 🧪 **Fully Tested**: Comprehensive test suite with 100% coverage
- 📖 **Well Documented**: Complete API documentation with examples

🚀 Quick Start
-------------

[](#-quick-start)

### Installation

[](#installation)

```
composer require supabase/laravel-auth
```

### Publish Configuration

[](#publish-configuration)

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

### Environment Setup

[](#environment-setup)

Add to your `.env` file:

```
# Required
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_ANON_KEY=your-anon-key
SUPABASE_SERVICE_KEY=your-service-key
SUPABASE_JWT_SECRET=your-jwt-secret

# Optional - Enterprise Features
SUPABASE_CACHE_ENABLED=true
SUPABASE_CACHE_STORE=redis
SUPABASE_RATE_LIMITING_ENABLED=true
SUPABASE_CIRCUIT_BREAKER_ENABLED=true
```

### Run Migrations

[](#run-migrations)

```
php artisan migrate
```

### Validate Configuration

[](#validate-configuration)

```
php artisan supabase:validate-config --show-summary --test-connection
```

📋 Configuration
---------------

[](#-configuration)

### Basic Auth Configuration

[](#basic-auth-configuration)

Update your `config/auth.php`:

```
'defaults' => [
    'guard' => 'supabase',
    'passwords' => 'users',
],

'guards' => [
    'supabase' => [
        'driver' => 'supabase',
        'provider' => 'supabase',
    ],
],

'providers' => [
    'supabase' => [
        'driver' => 'supabase',
        'model' => Supabase\\LaravelAuth\\Models\\SupabaseUser::class,
    ],
],
```

### Enterprise Configuration

[](#enterprise-configuration)

The package provides extensive configuration options in `config/supabase-auth.php`:

```
return [
    // Core Supabase settings
    'url' => env('SUPABASE_URL'),
    'anon_key' => env('SUPABASE_ANON_KEY'),
    'service_key' => env('SUPABASE_SERVICE_KEY'),
    'jwt' => [
        'secret' => env('SUPABASE_JWT_SECRET'),
        'algorithm' => env('SUPABASE_JWT_ALGORITHM', 'HS256'),
        'ttl' => env('SUPABASE_JWT_TTL', 3600),
    ],

    // Enterprise features
    'rate_limiting' => [
        'enabled' => env('SUPABASE_RATE_LIMITING_ENABLED', true),
        'login' => [
            'max_attempts' => env('SUPABASE_LOGIN_MAX_ATTEMPTS', 5),
            'decay_minutes' => env('SUPABASE_LOGIN_DECAY_MINUTES', 15),
        ],
    ],

    'circuit_breaker' => [
        'enabled' => env('SUPABASE_CIRCUIT_BREAKER_ENABLED', true),
        'failure_threshold' => env('SUPABASE_CB_FAILURE_THRESHOLD', 5),
        'recovery_timeout' => env('SUPABASE_CB_RECOVERY_TIMEOUT', 60),
    ],

    'cache' => [
        'enabled' => env('SUPABASE_CACHE_ENABLED', true),
        'store' => env('SUPABASE_CACHE_STORE', 'redis'),
        'ttl' => [
            'user_data' => env('SUPABASE_CACHE_USER_TTL', 300),
            'jwt_validation' => env('SUPABASE_CACHE_JWT_TTL', 60),
        ],
    ],
];
```

💡 Usage Examples
----------------

[](#-usage-examples)

### User Registration

[](#user-registration)

```
use Supabase\LaravelAuth\Facades\SupabaseAuth;

// Using the facade
$response = SupabaseAuth::signUp('user@example.com', 'password123', [
    'name' => 'John Doe',
    'timezone' => 'America/New_York',
]);

// Using API endpoint
POST /auth/supabase/register
{
    "email": "user@example.com",
    "password": "password123",
    "name": "John Doe"
}
```

### User Authentication

[](#user-authentication)

```
use Illuminate\Support\Facades\Auth;

// Using Laravel's Auth facade (recommended)
if (Auth::attempt(['email' => $email, 'password' => $password])) {
    $user = Auth::user();
    // User is authenticated
}

// Using API endpoint
POST /auth/supabase/login
{
    "email": "user@example.com",
    "password": "password123",
    "remember": true
}
```

### Working with Users

[](#working-with-users)

```
$user = Auth::user();

// Access Supabase-specific data
$supabaseData = $user->getSupabaseData();
$userId = $user->getSupabaseUserId();
$metadata = $user->getSupabaseUserMetadata();

// User attributes and methods
$user->hasVerifiedEmail();
$user->isAdmin();
$user->hasRole('premium');
$user->getTimezone();
$user->getPreferences();

// Update user profile
$user->updateSupabaseProfile(['name' => 'New Name']);

// Change password
$user->changeSupabasePassword('new-password');
```

### OAuth Authentication

[](#oauth-authentication)

```
// Generate OAuth URL
$oauthUrl = SupabaseAuth::signInWithOAuth('google', [
    'redirectTo' => config('app.url') . '/auth/callback',
    'scopes' => 'email profile',
]);

return redirect($oauthUrl);
```

### Password Reset

[](#password-reset)

```
// Request password reset
SupabaseAuth::resetPasswordForEmail('user@example.com', $redirectUrl);

// Update password (with access token)
SupabaseAuth::updatePassword($accessToken, 'new-password');
```

### Email Verification

[](#email-verification)

```
// Verify OTP
$response = SupabaseAuth::verifyOtp('user@example.com', '123456', 'email');

// Resend verification email
SupabaseAuth::resendOtp('user@example.com', 'signup');
```

🔒 Route Protection
------------------

[](#-route-protection)

### Basic Middleware

[](#basic-middleware)

```
use Supabase\LaravelAuth\Http\Middleware\AuthenticateSupabase;

Route::middleware('auth:supabase')->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
    Route::get('/profile', [ProfileController::class, 'show']);
});
```

### Advanced Middleware

[](#advanced-middleware)

```
use Supabase\LaravelAuth\Http\Middleware\EnsureTokenIsValid;

// Ensure token is valid and auto-refresh if needed
Route::middleware(EnsureTokenIsValid::class)->group(function () {
    Route::get('/api/user', [ApiController::class, 'user']);
});
```

### Guest-Only Routes

[](#guest-only-routes)

```
use Supabase\LaravelAuth\Http\Middleware\RedirectIfAuthenticated;

Route::middleware(RedirectIfAuthenticated::class)->group(function () {
    Route::get('/login', [AuthController::class, 'showLoginForm']);
    Route::get('/register', [AuthController::class, 'showRegistrationForm']);
});
```

🛠️ Management Commands
----------------------

[](#️-management-commands)

### Validate Configuration

[](#validate-configuration-1)

```
# Basic validation
php artisan supabase:validate-config

# With detailed output
php artisan supabase:validate-config --show-summary --test-connection
```

### Test Connection

[](#test-connection)

```
# Test Supabase connection
php artisan supabase:test-connection

# With detailed diagnostics
php artisan supabase:test-connection --detailed --reset-circuit-breaker
```

### Cache Management

[](#cache-management)

```
# Clear all cache
php artisan supabase:clear-cache

# Clear specific user cache
php artisan supabase:clear-cache --user=user-id

# Show cache statistics
php artisan supabase:clear-cache --stats
```

📊 Monitoring &amp; Observability
--------------------------------

[](#-monitoring--observability)

### Health Checks

[](#health-checks)

```
$health = app(SupabaseClient::class)->healthCheck();

// Returns:
// [
//     'status' => 'healthy',
//     'response_time_ms' => 45.2,
//     'timestamp' => '2024-01-01T12:00:00Z'
// ]
```

### Circuit Breaker Status

[](#circuit-breaker-status)

```
$circuitBreaker = app(CircuitBreakerInterface::class);

if ($circuitBreaker->isOpen('supabase')) {
    // Service is temporarily unavailable
}
```

### Rate Limiting Info

[](#rate-limiting-info)

```
$rateLimiter = app(RateLimiterInterface::class);
$status = $rateLimiter->getStatus($key, $maxAttempts);

// Returns attempt count, retries left, etc.
```

🔧 Customization
---------------

[](#-customization)

### Custom User Model

[](#custom-user-model)

Create your own user model:

```
use Supabase\LaravelAuth\Traits\HasSupabaseAuth;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use HasSupabaseAuth;

    // Your custom implementation
    protected $fillable = [
        'id', 'email', 'name', 'company_id', 'role',
    ];

    public function company()
    {
        return $this->belongsTo(Company::class);
    }
}
```

Update configuration:

```
'providers' => [
    'supabase' => [
        'driver' => 'supabase',
        'model' => App\\Models\\User::class,
    ],
],
```

### Event Listeners

[](#event-listeners)

Listen to authentication events:

```
use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Events\Logout;

Event::listen(Login::class, function (Login $event) {
    // User logged in
    $user = $event->user;
    $guard = $event->guard; // 'supabase'
});

Event::listen(Logout::class, function (Logout $event) {
    // User logged out
});
```

### Custom Services

[](#custom-services)

Extend or replace services by binding in your service provider:

```
$this->app->bind(SupabaseAuthInterface::class, CustomSupabaseAuth::class);
$this->app->bind(CircuitBreakerInterface::class, CustomCircuitBreaker::class);
```

🧪 Testing
---------

[](#-testing)

### Run Tests

[](#run-tests)

```
cd packages/laravel-supabase-auth
composer install
vendor/bin/phpunit
```

### Test Coverage

[](#test-coverage)

```
vendor/bin/phpunit --coverage-html coverage
```

### Code Quality

[](#code-quality)

```
# PHPStan analysis
vendor/bin/phpstan analyse

# Code formatting
vendor/bin/php-cs-fixer fix
```

### Testing in Your App

[](#testing-in-your-app)

Mock the Supabase client in your tests:

```
use Supabase\LaravelAuth\Services\SupabaseClient;

public function test_user_registration()
{
    $mockClient = Mockery::mock(SupabaseClient::class);
    $mockClient->shouldReceive('request')
        ->andReturn(['user' => ['id' => 'test-id']]);

    $this->app->instance(SupabaseClient::class, $mockClient);

    $response = $this->postJson('/auth/supabase/register', [
        'email' => 'test@example.com',
        'password' => 'password123',
    ]);

    $response->assertSuccessful();
}
```

📚 API Reference
---------------

[](#-api-reference)

### SupabaseAuth Service

[](#supabaseauth-service)

```
interface SupabaseAuthInterface
{
    public function signUp(string $email, string $password, array $data = []): array;
    public function signIn(string $email, string $password): array;
    public function signOut(string $accessToken): array;
    public function refreshToken(string $refreshToken): array;
    public function getUser(string $accessToken): array;
    public function updateUser(string $accessToken, array $data): array;
    public function resetPasswordForEmail(string $email, ?string $redirectTo = null): array;
    public function updatePassword(string $accessToken, string $newPassword): array;
    public function verifyOtp(string $email, string $token, string $type = 'email'): array;
    public function resendOtp(string $email, string $type = 'signup'): array;
    public function signInWithOAuth(string $provider, array $options = []): string;
    public function verifyToken(string $token): array;
    public function getUserById(string $userId): array;
    public function deleteUser(string $userId): array;
}
```

### Available API Endpoints

[](#available-api-endpoints)

MethodEndpointDescriptionAuth RequiredPOST`/auth/supabase/register`User registrationNoPOST`/auth/supabase/login`User loginNoPOST`/auth/supabase/logout`User logoutNoPOST`/auth/supabase/refresh`Refresh access tokenNoGET`/auth/supabase/user`Get authenticated userYesPOST`/auth/supabase/password/reset`Request password resetNoPOST`/auth/supabase/password/update`Update passwordYesPOST`/auth/supabase/otp/verify`Verify OTPNoPOST`/auth/supabase/otp/resend`Resend OTPNoGET`/auth/supabase/callback`OAuth callbackNo🚨 Error Handling
----------------

[](#-error-handling)

The package provides specific exceptions:

```
use Supabase\LaravelAuth\Exceptions\AuthenticationException;
use Supabase\LaravelAuth\Exceptions\ConfigurationException;
use Supabase\LaravelAuth\Exceptions\CircuitBreakerException;

try {
    SupabaseAuth::signIn($email, $password);
} catch (AuthenticationException $e) {
    // Handle authentication errors
    if ($e->getCode() === 401) {
        return response()->json(['error' => 'Invalid credentials'], 401);
    }
} catch (CircuitBreakerException $e) {
    // Handle service unavailable
    return response()->json(['error' => 'Service temporarily unavailable'], 503);
}
```

🔧 Troubleshooting
-----------------

[](#-troubleshooting)

### Common Issues

[](#common-issues)

1. **Configuration Validation Failed**

    ```
    php artisan supabase:validate-config --show-summary
    ```
2. **Connection Issues**

    ```
    php artisan supabase:test-connection --detailed
    ```
3. **Cache Issues**

    ```
    php artisan supabase:clear-cache --stats
    ```
4. **Circuit Breaker Open**

    ```
    php artisan supabase:test-connection --reset-circuit-breaker
    ```

### Debug Mode

[](#debug-mode)

Enable debug logging:

```
SUPABASE_LOG_LEVEL=debug
SUPABASE_MONITORING_ENABLED=true
```

🤝 Contributing
--------------

[](#-contributing)

1. Fork the repository
2. Create a feature branch: `git checkout -b feature/amazing-feature`
3. Make your changes and add tests
4. Run the test suite: `composer test`
5. Run code quality checks: `composer analyse && composer format`
6. Commit your changes: `git commit -m 'Add amazing feature'`
7. Push to the branch: `git push origin feature/amazing-feature`
8. Submit a pull request

📄 License
---------

[](#-license)

This package is open-sourced software licensed under the [MIT license](LICENSE.md).

🙏 Acknowledgments
-----------------

[](#-acknowledgments)

- Built for the [Supabase](https://supabase.com) ecosystem
- Inspired by Laravel's elegant authentication system
- Thanks to all contributors and the open-source community

📞 Support
---------

[](#-support)

- 🐛 [Issue Tracker](https://github.com/Draidel/laravel-supabase-auth/issues)
- 💬 [Discussions](https://github.com/Draidel/laravel-supabase-auth/discussions)
- 🌟 [Give us a star](https://github.com/Draidel/laravel-supabase-auth/laravel-auth) if this package helped you!

---

Made with ❤️ by [Draidel.com](https://www.draidel.com)

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance54

Moderate activity, may be stable

Popularity10

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity36

Early-stage or recently created project

 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

Unknown

Total

1

Last Release

295d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1a562ed4423266adcd6caf3a62fc8b00a802dcc4056a87fefde2bca8bd3d2c0e?d=identicon)[draidel](/maintainers/draidel)

---

Top Contributors

[![ariel-rajmaliuk](https://avatars.githubusercontent.com/u/11020595?v=4)](https://github.com/ariel-rajmaliuk "ariel-rajmaliuk (10 commits)")

---

Tags

jwtlaravelauthAuthenticationoauthenterprisesupabase

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/draidel-laravel-supabase-auth/health.svg)

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

###  Alternatives

[auth0/login

Auth0 Laravel SDK. Straight-forward and tested methods for implementing authentication, and accessing Auth0's Management API endpoints.

2745.0M3](/packages/auth0-login)[ellaisys/aws-cognito

AWS Cognito package that allows Auth and other related features using the AWS SDK for PHP

120220.7k1](/packages/ellaisys-aws-cognito)[benbjurstrom/cognito-jwt-guard

A laravel auth guard for JSON Web Tokens issued by Amazon AWS Cognito

1113.1k](/packages/benbjurstrom-cognito-jwt-guard)

PHPackages © 2026

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