Weave Code
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

Laravel Multiple Guards Laravel Package

shiftechafrica/laravel-multiple-guards

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require shiftechafrica/laravel-multiple-guards
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="ShiftechAfrica\MultipleGuards\MultipleGuardsServiceProvider"
    
  2. Configure Guards: Edit config/auth.php and define your additional guards (e.g., admin, api). Example:

    'guards' => [
        'web' => ['driver' => 'session', 'provider' => 'users'],
        'admin' => ['driver' => 'session', 'provider' => 'admins'],
        'api' => ['driver' => 'token', 'provider' => 'users'],
    ],
    
  3. First Use Case: Use the Guard facade to switch between guards dynamically:

    use ShiftechAfrica\MultipleGuards\Facades\Guard;
    
    // Check auth for 'admin' guard
    if (Guard::guard('admin')->check()) {
        // Admin-specific logic
    }
    

Implementation Patterns

Dynamic Guard Switching

  • Middleware: Create middleware to switch guards based on request context (e.g., route prefix):

    public function handle($request, Closure $next) {
        Guard::setGuard('admin');
        return $next($request);
    }
    

    Register in app/Http/Kernel.php:

    'admin' => \App\Http\Middleware\AdminGuard::class,
    
  • Service Providers: Override the default guard in boot():

    Guard::setGuard('api');
    

Provider Integration

  • Extend Illuminate\Contracts\Auth\Authenticatable for multi-guard models:

    use ShiftechAfrica\MultipleGuards\Traits\MultiGuardAuthenticatable;
    
    class Admin extends Model implements Authenticatable {
        use MultiGuardAuthenticatable;
    }
    
  • Custom Providers: Define providers in config/auth.php:

    'providers' => [
        'users' => ['driver' => 'eloquent', 'model' => User::class],
        'admins' => ['driver' => 'eloquent', 'model' => Admin::class],
    ],
    

API/SPA Workflows

  • Token Guards: Use api guard for stateless token auth:
    Guard::guard('api')->attempt(['email' => 'user@example.com', 'password' => 'password']);
    
  • Session Guards: Use web guard for traditional sessions.

Blade Directives

  • Dynamic auth checks in views:
    @auth('admin')
        <p>Admin Dashboard</p>
    @endauth
    

Gotchas and Tips

Pitfalls

  1. Guard Context Leaks:

    • Avoid mixing guards in a single request (e.g., Guard::guard('web') after Guard::guard('admin')). Reset with:
      Guard::setGuard(null); // Reverts to default
      
  2. Model Binding Issues:

    • Ensure models implement MultiGuardAuthenticatable trait for Auth::guard()->user() to work across guards.
  3. Session Conflicts:

    • If using session driver, clear sessions manually when switching guards:
      session()->forget('guard');
      

Debugging

  • Guard Resolution: Log the active guard to debug:

    \Log::info('Active guard:', ['guard' => Guard::getGuard()]);
    
  • Provider Errors: Verify config/auth.php providers match your models:

    // Throws: "Provider [admins] not found."
    

Extension Points

  1. Custom Guard Logic: Extend ShiftechAfrica\MultipleGuards\Guard to add guard-specific logic:

    class CustomGuard extends Guard {
        public function customMethod() { ... }
    }
    
  2. Middleware Overrides: Override Guard::setGuard() in middleware to enforce guard policies:

    public function handle($request, Closure $next) {
        if (!Guard::guard('admin')->check()) {
            abort(403);
        }
        return $next($request);
    }
    
  3. Testing: Mock guards in tests:

    Guard::shouldReceive('guard')->andReturn(Mockery::mock('overload', Guard::class));
    

Config Quirks

  • Default Guard: Set DEFAULT_GUARD in config/auth.php to avoid null guard issues:

    'DEFAULT_GUARD' => 'web',
    
  • Guard Drivers: Ensure drivers (e.g., token, session) are properly configured in config/auth.php.

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.
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver