Skip to content

Conversation

@Boorinio
Copy link
Contributor

This pull request introduces the Conditionable trait to the Laravel Route class, allowing developers to add conditional logic when defining routes. Consider the following:

Route::middleware('shop')
    ->domain('{shop}.domain.com')
    ->when(App::isProduction(), function ($route) {
        $route->whereIn('shop', app(ShopService::class)->getShopSlugs());   
    });

No Breaking Changes

This addition does not alter any existing functionality of the Route class. The Conditionable trait is introduced as an optional feature that will only be applied when explicitly used by developers. Existing routes will continue to work as expected without any modifications.

P.S. tests included.

Thanks for your time

@Boorinio Boorinio changed the title Adds conditional to routes [11.x] Adds conditional to routes Nov 24, 2024
@taylorotwell taylorotwell merged commit 401798e into laravel:11.x Nov 25, 2024
37 checks passed
@Boorinio
Copy link
Contributor Author

@taylorotwell Thank you, much appreciated!!

@Eyad-Bereh
Copy link

Can you please explain how will this feature be useful? Any specific use cases you were thinking of?

@edalzell
Copy link

Can you please explain how will this feature be useful? Any specific use cases you were thinking of?

In my case I have a route that's only used in testing, this is perfect for that.

@Eyad-Bereh
Copy link

Eyad-Bereh commented Nov 26, 2024

Can you please explain how will this feature be useful? Any specific use cases you were thinking of?

In my case I have a route that's only used in testing, this is perfect for that.

If you need specific routes for testing, shouldn't you just define them inside the test?
I'm talking about something like

$router = $this->getRouter();
$router->get('foo/bar', function () {
return 'hello';
});
$this->assertSame('hello', $router->dispatch(Request::create('foo/bar', 'GET'))->getContent());

instead of hardcoding them inside your project code?

Comment on lines +954 to +965
$route->when(true, function ($route) {
$route->whereIn('subdomain', [
'one',
'two',
]);
});

$request = Request::create('test.awesome.test', 'GET');
$this->assertFalse($route->matches($request));

$request = Request::create('one.awesome.test', 'GET');
$this->assertTrue($route->matches($request));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test doesn't actually test if when() works but if matches() works—this is counterintuitive to have in this PR

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants