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

Logged In Redirection Bundle Laravel Package

a5sys/logged-in-redirection-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require a5sys/logged-in-redirection-bundle
    
  2. Register the Bundle Add to config/bundles.php (Laravel 5.4+) or AppKernel.php (Symfony):

    A5sys\LoggedInRedirectionBundle\LoggedInRedirectionBundle::class => ['all' => true],
    
  3. Configure Routes Add to config/packages/logged_in_redirection.yaml (or config.yml in Symfony):

    logged_in_redirection:
        route_name: "fos_user_security_login"  # Route to check for logged-in users
        redirect_route_name: "homepage"       # Route to redirect to
    
  4. First Use Case A user bookmarks the login page (/login). After logging in, they return to the bookmark and see the login form again. The bundle automatically redirects them to homepage (e.g., /).


Implementation Patterns

Core Workflow

  1. Trigger Logic The bundle hooks into Symfony’s kernel.request event. When a user visits the configured route_name (e.g., /login) after authentication, the bundle checks if they’re logged in. If they are, it redirects to redirect_route_name.

  2. Integration with Authentication

    • Works seamlessly with FOSUserBundle (default example) or any Symfony/Laravel auth system.
    • For Laravel, use the Symfony bridge (e.g., symfony/http-foundation) to integrate with Laravel’s auth middleware.
  3. Dynamic Redirects Override the redirect_route_name per request via a twig variable or controller logic:

    # config/packages/logged_in_redirection.yaml
    logged_in_redirection:
        route_name: "fos_user_security_login"
        redirect_route_name: "dashboard"  # Default
    

    Or dynamically in a controller:

    $this->get('logged_in_redirection.redirector')->setRedirectRoute('custom_dashboard');
    
  4. Excluding Routes Disable the redirect for specific routes by tagging them in routing:

    # config/routes.yaml
    login:
        path: /login
        controller: App\Controller\LoginController::index
        methods: GET
        defaults:
            _logged_in_redirection_exclude: true
    
  5. Laravel-Specific Adaptation

    • Middleware Approach: Wrap the bundle’s logic in Laravel middleware for finer control:
      // app/Http/Middleware/LoggedInRedirect.php
      public function handle($request, Closure $next) {
          if (Auth::check() && $request->is('login')) {
              return redirect()->route('homepage');
          }
          return $next($request);
      }
      
    • Service Provider: Bind the bundle’s services to Laravel’s container:
      // app/Providers/AppServiceProvider.php
      public function register() {
          $this->app->bind(
              'logged_in_redirection.redirector',
              A5sys\LoggedInRedirectionBundle\Redirector::class
          );
      }
      

Gotchas and Tips

Pitfalls

  1. Route Name Mismatch

    • Issue: The bundle fails silently if route_name doesn’t exist.
    • Fix: Verify the route name in config/packages/logged_in_redirection.yaml matches your routing (e.g., fos_user_security_login for FOSUserBundle).
  2. Caching Headaches

    • Issue: Bookmarked login pages may still show the login form due to cached redirects.
    • Fix: Ensure redirect_route_name is a non-cacheable route (e.g., add stale-while-revalidate: 0 to cache headers).
  3. Laravel Auth Guard Conflicts

    • Issue: The bundle uses Symfony’s Security component. In Laravel, ensure the guard is properly bound:
      Auth::guard('web')->check(); // Explicit guard check
      
  4. CSRF Token Errors

    • Issue: Redirecting to a POST route (e.g., login) after a GET request may break CSRF tokens.
    • Fix: Use GET-only routes for redirects or regenerate tokens on redirect.

Debugging Tips

  1. Enable Debug Mode Add this to config/packages/logged_in_redirection.yaml:

    logged_in_redirection:
        debug: true  # Logs redirects to Symfony's profiler
    
  2. Check Events The bundle listens to kernel.request. Debug with:

    // In a controller or command
    $eventDispatcher = $this->get('event_dispatcher');
    $eventDispatcher->addListener('kernel.request', function($event) {
        dump($event->getRequest()->getPathInfo());
    });
    
  3. Override Redirector Extend the Redirector class to add custom logic:

    // src/Service/CustomRedirector.php
    namespace App\Service;
    use A5sys\LoggedInRedirectionBundle\Redirector as BaseRedirector;
    
    class CustomRedirector extends BaseRedirector {
        public function isRedirectable($request) {
            if ($request->getPathInfo() === '/admin') {
                return false; // Skip redirect for /admin
            }
            return parent::isRedirectable($request);
        }
    }
    

    Bind it in config/services.yaml:

    services:
        logged_in_redirection.redirector: '@App\Service\CustomRedirector'
    

Extension Points

  1. Custom Redirect Logic Subscribe to the logged_in_redirection.redirect event:

    // config/services.yaml
    services:
        App\EventListener\CustomRedirectListener:
            tags:
                - { name: kernel.event_listener, event: logged_in_redirection.redirect, method: onRedirect }
    
    // src/EventListener/CustomRedirectListener.php
    public function onRedirect(RedirectEvent $event) {
        if ($event->getUser()->hasRole('ADMIN')) {
            $event->setRedirectRoute('admin_dashboard');
        }
    }
    
  2. Multi-Tenant Redirects Dynamically set redirect_route_name based on tenant:

    $redirector = $this->get('logged_in_redirection.redirector');
    $redirector->setRedirectRoute("tenant_{$tenantId}_dashboard");
    
  3. AJAX Handling Exclude AJAX requests from redirects:

    logged_in_redirection:
        exclude_ajax: true
    

    Or in custom logic:

    if ($request->isXmlHttpRequest()) {
        return $next($request);
    }
    
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
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