logo
podcast Podcast
get help Get Unstuck

Route method order matters in certain cases

Another one I learned the hard way

Joel Clermont
Joel Clermont
2024-09-13

A while back, I shared an approach I use with creating dynamic routes inside a test class for testing middleware. If you haven't seen that tip, I recommend clicking through to read it first for context.

Today, I want to add on a detail that I bumped into recently with this approach to testing middleware.

Instead of just creating a basic dynamic route to attach my middleware, I also wanted to name the route because it used route model binding and I wanted to use the route helper to generate the URL in my test methods.

What I discovered is that when creating a route dynamically like this, the order of the methods in the fluent chain matters.

For example, if I specified the name as the last method in the fluent method call, the name was not registered in the route collection, and I'd get an error trying to access the route by name in my test.

On the other hand, if I specify the name first when defining the route, it would work as expected.

Here's the two versions side by side for comparison:

class SomeMiddlewareClassTest extends IntegrationTestCase
{
    protected function setUp(): void
    {
        parent::setUp();
        
        // ❌️ name at the end does not work
        Route::get('/dummy-test-route/{user}', function (User $user) {
            return '';
        })->middleware(['web', SomeMiddlewareClass::class])
            ->name('named-route');
        
        // ✅️️ name at the beginning works
        Route::name('named-route')
            ->get('/dummy-test-route/{user}', function (User $user) {
                return '';
            })->middleware(['web', SomeMiddlewareClass::class]);
    }
    
    // test methods not included...
}

I found this confusing, because in the routes file, the order makes no difference at all. But when building something dynamically like this, the order matters.

Here to help,

Joel

P.S. Another tip on testing? Wow, this guy loves testing. Guilty as charged. Want help getting started with testing?

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.