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

To leverage symfony/routing in Laravel, start by installing the package:

composer require symfony/routing

First Use Case: Route Matching & URL Generation

Laravel already abstracts routing, but you can use Symfony's routing directly for custom logic:

use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\Generator\UrlGenerator;
use Symfony\Component\Routing\RequestContext;

// Define routes
$routes = new RouteCollection();
$routes->add('blog_show', new Route('/blog/{slug}', [
    '_controller' => 'App\Http\Controllers\BlogController@show',
]));

// Match a request
$context = new RequestContext();
$matcher = new UrlMatcher($routes, $context);
$params = $matcher->match('/blog/hello-world');

// Generate a URL
$generator = new UrlGenerator($routes, $context);
$url = $generator->generate('blog_show', ['slug' => 'hello-world']);

Where to Look First

  • Documentation: Symfony Routing Docs
  • Laravel Integration: Use Illuminate\Routing\Router for Laravel-specific routing, but Symfony's routing is useful for:
    • Custom route matching logic
    • Generating URLs programmatically
    • Advanced route constraints

Implementation Patterns

1. Route Definitions

Define routes programmatically or via YAML/JSON (Symfony's format, but adaptable to Laravel):

// Programmatic route definition
$route = new Route('/user/{id}', [
    '_controller' => 'App\Http\Controllers\UserController@show',
    'methods' => ['GET', 'HEAD'],
    'requirements' => ['id' => '\d+'],
]);
$routes->add('user_show', $route);

2. Request Context Management

Use RequestContext to manage global routing parameters (e.g., base URL, scheme):

$context = new RequestContext();
$context->setBaseUrl('https://example.com');
$context->setScheme('https');

3. URL Generation with Query Parameters

Generate URLs with query strings dynamically:

$url = $generator->generate('blog_show', [
    'slug' => 'post-1',
], UrlGenerator::ABSOLUTE_URL, [
    'page' => 2,
    'sort' => 'desc',
]);
// Output: /blog/post-1?page=2&sort=desc

4. Route Matching with HTTP Method

Match routes while respecting HTTP methods:

$matcher = new UrlMatcher($routes, $context);
$params = $matcher->matchRequest($request); // Uses $request->getMethod()

5. Integration with Laravel Controllers

Use Symfony's routing to generate URLs in controllers:

use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

class BlogController extends Controller
{
    public function show(UrlGeneratorInterface $urlGenerator)
    {
        $url = $urlGenerator->generate('blog_show', ['slug' => 'test']);
        return view('blog.show')->with('url', $url);
    }
}

6. Dynamic Route Loading

Load routes from external sources (e.g., API responses, database):

$routes = new RouteCollection();
foreach ($apiRoutes as $name => $routeData) {
    $routes->add($name, new Route($routeData['path'], $routeData['defaults']));
}

7. Route Constraints and Requirements

Define constraints for route parameters:

$route = new Route('/post/{year}/{month}/{day}', [], [
    'year' => '\d{4}',
    'month' => '(0[1-9]|1[0-2])',
    'day' => '(0[1-9]|[12][0-9]|3[01])',
]);

Gotchas and Tips

Pitfalls

  1. Case Sensitivity in Host Matching

    • Host-based routes are case-sensitive by default. Use RequestContext::setHost() carefully.
    • Fix: Normalize hostnames (e.g., strtolower()) if case-insensitive matching is needed.
  2. Query Parameter Handling

    • Numeric query keys (e.g., ?0=value) may be renumbered. Use associative arrays for stability:
      $url = $generator->generate('route_name', [], UrlGenerator::ABSOLUTE_URL, ['page' => 1]);
      
  3. Circular References in Route Collections

    • Avoid circular references when adding routes dynamically. Use RouteCollection::addCollection() for nested routes.
  4. URL Generation with Absolute Paths

    • UrlGenerator::ABSOLUTE_URL generates full URLs, but ensure RequestContext is properly configured with baseUrl and scheme.
  5. Route Overrides

    • Adding a route with the same name as an existing one silently replaces it. Use RouteCollection::get() to check for conflicts.

Debugging Tips

  1. Dump Route Parameters Use var_dump($matcher->match('/path')) to inspect matched parameters and debug issues.

  2. Check Route Requirements If a route isn't matching, verify requirements (e.g., regex constraints) and defaults.

  3. Enable Route Debugging in Laravel Use Laravel's built-in route listing:

    php artisan route:list
    

    Or dump Symfony's route collection:

    dd($routes->getIterator());
    

Configuration Quirks

  1. Request Context Persistence RequestContext is stateless. Recreate it for each request or persist it (e.g., in middleware).

  2. Host and Scheme Defaults If RequestContext isn't configured, generated URLs may omit the scheme or host. Set defaults:

    $context->setScheme('https');
    $context->setHost('example.com');
    
  3. Route Name Conflicts Laravel and Symfony may handle route names differently. Prefix Symfony routes:

    $routes->add('symfony_blog_show', $route);
    

Extension Points

  1. Custom Route Loaders Extend RouteLoaderInterface to load routes from custom sources (e.g., database, API).

  2. Route Compilation Use RouteCompiler to pre-compile routes for performance-critical applications.

  3. Middleware Integration Integrate Symfony's routing with Laravel middleware by wrapping UrlMatcher or UrlGenerator in a service provider:

    $this->app->singleton(UrlGeneratorInterface::class, function ($app) {
        return new UrlGenerator($app['routes'], $app['request_context']);
    });
    
  4. Attribute-Based Routing Leverage Symfony's attribute-based routing (v8+) in Laravel by creating a custom loader:

    use Symfony\Component\Routing\Loader\AttributeLoader;
    
    $loader = new AttributeLoader($controllerClass);
    $routes = $loader->load(__DIR__.'/../src/Http/Controllers');
    
  5. Route Caching Cache compiled routes for better performance:

    $compiler = new RouteCompiler();
    $compiledRoutes = $compiler->compile($routes);
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle