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 Attributes Laravel Package

spatie/laravel-route-attributes

Register Laravel routes using PHP 8 attributes on controller methods (Get/Post/etc.). Automatically scans configured controller directories and registers routes without manual Route:: definitions. Includes config publishing and optional enabling/disabling of auto registration.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-route-attributes
    

    Publish the config (optional):

    php artisan vendor:publish --provider="Spatie\RouteAttributes\RouteAttributesServiceProvider"
    
  2. First Use Case: Replace a basic routes/web.php route:

    // Before: routes/web.php
    Route::get('/dashboard', [DashboardController::class, 'index']);
    
    // After: DashboardController.php
    use Spatie\RouteAttributes\Attributes\Get;
    
    class DashboardController {
        #[Get('/dashboard')]
        public function index() { ... }
    }
    
  3. Where to Look First:

    • Review the README for attribute syntax.
    • Check config/route-attributes.php for customization options (e.g., namespace scanning).
    • Run php artisan route:list to verify auto-registered routes.

Implementation Patterns

Core Workflows

  1. Attribute-Based Routing:

    • Replace Route::get(), Route::post(), etc., with attributes:
      #[Get('/users/{id}', name: 'users.show')]
      public function show(User $user) { ... }
      
    • Supports all HTTP methods (Get, Post, Put, Delete, Patch, Options, Head).
  2. Middleware Integration:

    • Apply middleware via attributes:
      #[Get('/admin', middleware: ['auth', 'admin'])]
      public function adminDashboard() { ... }
      
    • Override global middleware for specific routes.
  3. Route Grouping:

    • Use RouteAttributesGroup for shared prefixes/middleware:
      use Spatie\RouteAttributes\Attributes\RouteAttributesGroup;
      
      #[RouteAttributesGroup(prefix: 'api/v1', middleware: ['api'])]
      class ApiV1Controller {
          #[Get('/users')]
          public function index() { ... }
      }
      
  4. Dynamic Route Parameters:

    • Leverage Laravel’s dependency injection for type-hinted parameters:
      #[Get('/posts/{post}')]
      public function show(Post $post) { ... }
      
  5. Route Caching:

    • Cache routes with php artisan route:cache (works seamlessly with attributes).

Integration Tips

  • Namespaces: Configure scanned_namespaces in config/route-attributes.php to auto-discover controllers.
  • API Resources: Combine with spatie/laravel-api-resource for attribute-driven API responses.
  • Testing: Use Route::getRoutes()->getByName() to assert routes in tests:
    $this->assertTrue(Route::getRoutes()->getByName('users.show')->count() > 0);
    

Gotchas and Tips

Pitfalls

  1. Namespace Scanning:

    • Forgetting to add a namespace to scanned_namespaces means routes won’t auto-register.
    • Fix: Run php artisan route:clear and check logs for missing routes.
  2. Route Overrides:

    • Explicit Route::get() calls in web.php take precedence over attributes.
    • Tip: Use #[Route(name: 'unique.name')] to avoid conflicts.
  3. Middleware Conflicts:

    • Global middleware (e.g., web) may clash with attribute-defined middleware.
    • Solution: Use middleware: ['except' => ['web']] to exclude global middleware.
  4. Caching Issues:

    • After adding new attributes, clear route cache:
      php artisan route:clear
      

Debugging

  • Route Not Found?:

    • Verify the controller is in a scanned_namespaces.
    • Check for typos in attribute names (e.g., #[Get] vs #[GET]).
    • Use php artisan route:list to inspect registered routes.
  • Attribute Not Recognized:

    • Ensure the package is properly installed and the service provider is registered in config/app.php.

Extension Points

  1. Custom Attributes:

    • Extend the package by creating your own attributes:
      #[Attribute]
      class CustomRoute extends Get {
          public function __construct(string $uri, array $options = []) {
              parent::__construct($uri, $options + ['custom' => true]);
          }
      }
      
  2. Route Filtering:

    • Use the RouteAttributesServiceProvider events to filter routes before registration:
      RouteAttributesServiceProvider::macro('registeringRoutes', function ($routes) {
          $routes->reject(fn ($route) => str_contains($route->uri(), 'disabled'));
      });
      
  3. Dynamic URI Generation:

    • Generate URLs using the route name (defined in name option):
      route('users.show', ['id' => 1]);
      

Performance Tips

  • Exclude Unused Controllers: Narrow scanned_namespaces to reduce scanning overhead.
  • Use Route Caching: Enable in production (ROUTE_CACHING=true in .env) for faster route resolution.
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