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 Route Discovery Laravel Package

spatie/laravel-route-discovery

Automatically discover Laravel routes by scanning controllers and views instead of manually defining them. Configure discovery in your routes files and use PHP attributes to customize names, middleware, and more for each discovered route.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Pros:

    • Aligns with Laravel’s convention-over-configuration philosophy, reducing boilerplate in routes/web.php or routes/api.php.
    • Leverages PHP attributes (PHP 8+), a modern, type-safe way to define route metadata (names, middleware, etc.) directly in controllers.
    • Complements Laravel’s existing route system (e.g., Route::get(), Route::resource()) without replacing it, enabling hybrid approaches.
    • Supports modular monoliths/microservices by scoping discovery to specific directories (e.g., Discover::controllers()->in(app_path('Modules/Api'))).
    • API-first friendly: Attributes can enforce consistent route naming/middleware for API endpoints (e.g., #[Route(name: 'api.v1.users.index')]).
  • Cons:

    • Tight coupling to Laravel: Not framework-agnostic; requires Laravel’s routing stack (e.g., Illuminate\Routing).
    • Attribute reflection overhead: May introduce minor performance costs during route registration (though negligible for most apps).
    • Limited dynamic route generation: Attributes are static; dynamic routes (e.g., Route::fallback()) still require manual definition.

Integration Feasibility

  • Low-risk for greenfield projects: Ideal for new Laravel apps where route organization is a priority.
  • Moderate risk for legacy systems:
    • Existing routes/*.php files must be refactored incrementally (attribute migration path exists).
    • Potential conflicts with custom route macros or third-party route packages (e.g., spatie/laravel-honeypot).
  • Database/ORM impact: None—routes are code-first, no schema changes required.

Technical Risk

Risk Area Severity Mitigation Strategy
Attribute parsing Low Test with PHP 8.0+; fallback to manual routes if needed.
Middleware conflicts Medium Audit existing middleware stacks pre-migration.
Caching interactions Low Clear route cache (php artisan route:clear) post-migration.
IDE support Low Attributes may not auto-complete in older IDEs (e.g., PHPStorm < 2021.3).
Testing impact Low Route tests may need updates for attribute-based names/middleware.

Key Questions

  1. Adoption Scope:
    • Will this replace all routes, or only new/non-critical ones (e.g., API controllers)?
    • How will legacy route files (e.g., routes/web.php) coexist with discovered routes?
  2. Attribute Strategy:
    • Should attributes replace or supplement existing route definitions (e.g., hybrid Route::get() + #[Route])?
    • Will custom attributes (e.g., @RateLimited) be needed, requiring extension?
  3. Performance:
    • Is route discovery bottlenecking application startup? (Benchmark with php artisan route:list --time.)
  4. Tooling:
    • How will Laravel Forge/Envoyer deployments handle attribute-based route changes?
    • Will Laravel Scout or API documentation tools (e.g., Swagger) need updates?
  5. Rollback Plan:
    • What’s the fallback if attributes cause runtime errors (e.g., invalid middleware)?

Integration Approach

Stack Fit

  • Laravel Core: Native integration with Laravel’s routing system (tested up to Laravel 11.x).
  • PHP Version: Requires PHP 8.0+ (for attributes). Compatible with Laravel’s supported versions.
  • Dependencies:
    • No conflicts with core Laravel packages (e.g., illuminate/routing).
    • Potential conflicts with route packages that modify RouteServiceProvider (e.g., spatie/laravel-permission route guards).
  • Frontend/Backend:
    • Backend-only: No impact on frontend frameworks (Vue/React) or static assets.
    • APIs: Ideal for REST/GraphQL APIs where route consistency is critical.

Migration Path

  1. Phase 1: Pilot (Low-Risk)

    • Start with non-critical controllers (e.g., admin panels, internal tools).
    • Example:
      // Before: routes/web.php
      Route::get('/admin/dashboard', [DashboardController::class, 'index']);
      
      // After: DashboardController.php
      class DashboardController {
          #[Route('/admin/dashboard', name: 'admin.dashboard')]
          public function index() { ... }
      }
      
    • Verify route discovery works via php artisan route:list.
  2. Phase 2: Incremental Adoption

    • Migrate API controllers first (higher ROI for consistency).
    • Replace Route::resource() with attribute-based discovery where needed:
      // Before: routes/api.php
      Route::resource('users', UserController::class)->middleware('auth:sanctum');
      
      // After: UserController.php
      class UserController {
          #[Route('/users', name: 'users.index', middleware: ['auth:sanctum'])]
          public function index() { ... }
      }
      
    • Update route tests to use #[Route] attributes.
  3. Phase 3: Full Migration

    • Replace remaining Route::get()/Route::post() calls with attributes.
    • Deprecate old route files (e.g., rename routes/web.php to routes/legacy.php).
    • Update documentation and IDE hints (e.g., PHPStorm route templates).

Compatibility

  • Laravel Features:
    • Middleware: Fully supported (#[Route(middleware: ['auth', 'throttle:60'])]).
    • Route Caching: Works with php artisan route:cache.
    • Route Model Binding: Compatible with implicit binding (e.g., #[Route('/users/{user}')]).
    • API Resources: No impact on Illuminate\Http\Resources.
  • Third-Party Packages:
    • Laravel Sanctum/Passport: Attributes can include auth middleware.
    • Laravel Horizon: Queue route discovery if using attribute-based job controllers.
    • Laravel Nova: Nova’s routes are auto-discovered; may need attribute overrides.
  • Custom Code:
    • Route macros: May need adjustments if they rely on Route::get() registration order.
    • Service providers: No changes needed unless modifying RouteServiceProvider.

Sequencing

  1. Pre-Migration:

    • Audit all route definitions (grep -r "Route::" routes/).
    • Backup routes/*.php files.
    • Test attribute parsing with a spike (e.g., one controller).
  2. During Migration:

    • Use feature flags to toggle discovery (e.g., config(['route-discovery.enabled' => env('DISCOVERY_ENABLED', false)]).
    • Run php artisan route:clear after each batch of changes.
  3. Post-Migration:

    • Remove old route files.
    • Update CI/CD pipelines to lint for missing attributes (e.g., phpstan rules).
    • Monitor route registration time (should not exceed 100ms).

Operational Impact

Maintenance

  • Pros:
    • Reduced boilerplate: Fewer lines in routes/*.php files.
    • Centralized route logic: All route metadata (names, middleware) lives with controllers.
    • Easier refactoring: Moving a controller updates its routes automatically.
  • Cons:
    • Attribute sprawl: Controllers may become cluttered with route annotations.
    • Tooling gaps: Limited IDE support for attribute-based route navigation (vs. Route::get()).
    • Debugging: Harder to trace route registration issues (e.g., "Why isn’t my attribute route showing up?").

Support

  • Developer Onboarding:
    • Pros: New devs learn routes by reading controller code (no routes/*.php files to memorize).
    • Cons: Requires familiarity with PHP attributes and Laravel’s routing system.
  • Troubleshooting:
    • Common issues:
      • Forgotten use Spatie\RouteDiscovery\Attributes\Route; import.
      • Middleware not found (e.g., typo in #[Route(middleware: ['auth:invalid'])]).
      • Route caching conflicts (php artisan route:clear).
    • Debugging tools:
      • php artisan route:list --name="*" to filter discovered routes.
      • php artisan route:clear to reset state.
  • Documentation:
    • Update internal docs to reflect attribute-based routes.
    • Add runbooks for:
      • "My attribute route disappeared!"
      • "How to migrate a Route::resource() to attributes."

Scaling

  • Performance:
    • Route registration: Attribute parsing adds **~5–
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport