Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/string backed enum in order by #54042

Conversation

liamduckett
Copy link
Contributor

I have an enum defined for fields that an API endpoint can be sorted by.

enum UserIndexSort: string
{
    case CreatedAt = 'created_at';
    case Name = 'name';
    case Email = 'email';
}

I'd like to pass this directly into the query builder, rather than having to convert to a string.

$sort = UserIndexSort::Name;

$users = User::query()
    ->orderBy($sort->value, 'desc')
    ->paginate();

The change I have made is quite deep in the framework. Illuminate/Database/Grammar::wrap is used in a lot of places. That being said, I do not see it being problematic - any BackedEnum being passed to wrap should be handled like so? Code will behave exactly as prior, unless a BackedEnum is passed.

As such, this change likely allows for BackedEnums to be used in other places too - happy to look through / update existing DocBlocks if that is desired. I think it will be, I just didn't want to do it too early, and then have the PR rejected.

@taylorotwell
Copy link
Member

Thanks for your pull request to Laravel!

Unfortunately, I'm going to delay merging this code for now. To preserve our ability to adequately maintain the framework, we need to be very careful regarding the amount of code we include.

If applicable, please consider releasing your code as a package so that the community can still take advantage of your contributions!

Comment on lines +85 to +87
if ($value instanceof BackedEnum) {
$value = $value->value;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

You could have used Illuminate\Support\enum_value():

Suggested change
if ($value instanceof BackedEnum) {
$value = $value->value;
}
$value = enum_value($value);

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