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

Routing Laravel Package

symfony/routing

Symfony Routing maps HTTP requests to routes and parameters, and generates URLs from route definitions. Define Route and RouteCollection, then use UrlMatcher to match paths and UrlGenerator to build links based on a RequestContext.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup in Laravel
1. **Installation**:
   ```bash
   composer require symfony/routing:^8.1

Laravel already includes Symfony's routing under the hood, but this standalone package is useful for custom routing logic outside the framework's default router. Note: Version ^8.1 is now recommended to leverage new features and security fixes.

  1. First Use Case: Define a route manually and generate URLs with the updated UrlGenerator:

    use Symfony\Component\Routing\Route;
    use Symfony\Component\Routing\RouteCollection;
    use Symfony\Component\Routing\Generator\UrlGenerator;
    
    $route = new Route('/blog/{slug}', [
        '_controller' => 'App\\Http\\Controllers\\BlogController@show',
    ]);
    $routes = new RouteCollection();
    $routes->add('blog_show', $route);
    
    $generator = new UrlGenerator($routes);
    $url = $generator->generate('blog_show', ['slug' => 'hello-world']);
    // Outputs: "/blog/hello-world"
    
  2. Where to Look First:


Implementation Patterns

1. Route Collections and Dynamic Loading

  • Pattern: Group routes logically (e.g., by module) and load them dynamically:
    $routes = new RouteCollection();
    $routes->addCollection($this->loadAdminRoutes());
    $routes->addCollection($this->loadApiRoutes());
    
    // Load from YAML/JSON/PHP files (Symfony's loaders)
    $loader = new YamlFileLoader($routes, new FileLocator(__DIR__.'/config'));
    $loader->load('routes.yaml');
    
  • New in 8.1: Use ContentLoaderTrait (now includes HostTrait) for host-based routing in custom loaders.

2. URL Generation in Controllers/Blades

  • Pattern: Generate URLs consistently across views and controllers:
    // In a controller
    $url = $generator->generate('blog_show', ['slug' => $post->slug], UrlGenerator::ABSOLUTE_URL);
    
    // In Blade templates (pass generator to view)
    <a href="{{ $url }}">Read Post</a>
    
  • Security Note: The UrlGenerator now validates regex requirements more strictly (see #cve-2026-45065).

3. Reverse Routing in Forms

  • Pattern: Use route names instead of hardcoded paths in forms:
    $form->action = $generator->generate('user_edit', ['id' => $user->id]);
    

4. Custom Route Matching Logic

  • Pattern: Extend UrlMatcher for complex requirements (e.g., multi-tenancy):
    $matcher = new UrlMatcher($routes, $context);
    $parameters = $matcher->match('/api/v1/users/123');
    $tenantId = $parameters['_tenant'] ?? null;
    

5. Integration with Laravel’s Router

  • Pattern: Use Symfony’s routing for non-HTTP routes (e.g., CLI commands or internal APIs):
    $cliRoutes = new RouteCollection();
    $cliRoutes->add('cli:backup', new Route('/backup', [], [], [], 'backup_command'));
    $generator = new UrlGenerator($cliRoutes);
    $command = $generator->generate('backup_command'); // Outputs: "/backup"
    

6. Route Requirements and Constraints

  • Pattern: Validate route parameters early with stricter regex handling:
    $route = new Route('/user/{id}', [], [], [], [], ['id' => '\d+']);
    $matcher = new UrlMatcher([$route], $context);
    $matcher->match('/user/123'); // Valid
    $matcher->match('/user/abc'); // Throws Exception (now more secure)
    
  • Fix for CVE-2026-45065: Ensure regex alternations (e.g., a|b) are properly anchored to avoid injection risks.

7. Localization and Route Prefixes

  • Pattern: Handle multi-language routes with HostTrait (now included in ContentLoaderTrait):
    $route = new Route('/{_locale}/blog/{slug}', [
        '_locale' => 'en|fr',
    ]);
    $context = new RequestContext();
    $context->setParameter('_locale', 'fr');
    $generator->generate('blog_show', ['slug' => 'bonjour'], [], UrlGenerator::ABSOLUTE_PATH);
    // Outputs: "/fr/blog/bonjour"
    

Gotchas and Tips

Pitfalls

  1. Case Sensitivity in Host Matching:

    • Host-based routes (e.g., api.example.com) are case-sensitive. Use HostTrait (now part of ContentLoaderTrait) or compile routes with case-insensitive flags.
    • Fix: Update RequestContext or use Route::setHost() with lowercase hosts.
  2. Query Parameters in URL Generation:

    • Query parameters (?_query=value) are not preserved by default. Use the _query option explicitly:
      $generator->generate('route_name', [], ['_query' => ['sort' => 'asc']]);
      
  3. Circular Route References:

    • Avoid infinite loops in redirects. Use UrlGenerator::ABSOLUTE_URL or validate routes before generation.
  4. Parameter Overwriting:

    • Default route parameters can be overwritten. Use UrlGenerator::INCLUDE_DEFAULT_VALUES:
      $generator->generate('route_name', [], UrlGenerator::INCLUDE_DEFAULT_VALUES);
      
  5. Performance with Large Route Collections:

    • Compile routes for production:
      $compiler = new RouteCompiler();
      $compiledRoutes = $compiler->compile($routes);
      $matcher = new CompiledUrlMatcher($compiledRoutes, $context);
      
  6. Regex Requirement Validation (New in 8.1):

    • Security Risk: Malicious regex patterns (e.g., a|.*) can cause performance issues or injection. Fix:
      • Anchor alternations: Use ^(a|b)$ instead of a|b.
      • Validate requirements in tests:
        $this->assertTrue(preg_match('/^\d+$/', '123')); // Safe
        $this->assertFalse(preg_match('/.*/', 'malicious')); // Rejected
        

Debugging Tips

  1. Inspect Matched Parameters:

    • Log UrlMatcher::match() output:
      try {
          $params = $matcher->match('/some/path');
      } catch (Exception $e) {
          logger()->error('Route match failed:', ['exception' => $e, 'path' => '/some/path']);
      }
      
  2. Validate Route Definitions:

    • Use RouteCollection::getIterator() to validate routes:
      foreach ($routes as $name => $route) {
          if (empty($route->getDefault('_controller'))) {
              logger()->warning("Route '$name' has no controller!");
          }
      }
      
  3. Test URL Generation:

    • Write unit tests for critical routes:
      public function testUrlGeneration()
      {
          $this->assertEquals(
              '/blog/hello-world',
              $generator->generate('blog_show', ['slug' => 'hello-world'])
          );
      }
      

Extension Points

  1. Custom Route Loaders:

    • Extend FileLocator or RouteLoaderInterface to load routes from custom sources (e.g., databases):
      class DatabaseRouteLoader implements RouteLoaderInterface
      {
          public function load($resource, string $type = null)
          {
              $routes = $this->fetchRoutesFromDatabase();
              return new RouteCollection($routes);
          }
      }
      
    • New in 8.1: Leverage ContentLoaderTrait for host-based routing in custom loaders.
  2. Middleware for Route Matching:

    • Wrap UrlMatcher in middleware:
      $matcher = new UrlMatcher($routes, $context);
      $matcher = new CustomMatcherDecorator($matcher);
      
      class CustomMatcherDecorator
      {
          public function match(string $pathinfo): array
          {
              $start = microtime(true);
      
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope