Skip to content

[9.x] Allow enum route bindings to have default values#44255

Merged
taylorotwell merged 4 commits into
laravel:9.xfrom
levu42:enum-route-binding-default-value
Sep 23, 2022
Merged

[9.x] Allow enum route bindings to have default values#44255
taylorotwell merged 4 commits into
laravel:9.xfrom
levu42:enum-route-binding-default-value

Conversation

@levu42

@levu42 levu42 commented Sep 22, 2022

Copy link
Copy Markdown
Contributor

It's possible already to bind route parameters to enums:

enum Status: string {
  case Published = 'published';
  case Draft = 'draft';
}

Route::get('/posts/{status}', function(Status $status) {});

However, it's not yet possible to have default values for optional parameters, as I discovered in #44249:

Route::get('/posts/{status?}', function(Status $status = Status::Published) {});

As discussed in #44249, I made the PR in a way, that it only applies, if the parameter is an enum, so it doesn't interfere with model binding in any way.

I'm not fully happy with the nested ternary operator, making it a bit more complex - I'm happy to change it so some other structure if you think something else is more readable.

I tried to keep the code change minimal to support this while having extensive tests, for them I looked at the existing backed enum binding tests and extended those.

Comment thread src/Illuminate/Routing/RouteDependencyResolverTrait.php

@BrandonSurowiec BrandonSurowiec left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Looks good to me!

@taylorotwell taylorotwell merged commit c4b61fa into laravel:9.x Sep 23, 2022
@taylorotwell

Copy link
Copy Markdown
Member

Thanks 👍

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.

3 participants