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

[11.x] Accept non-backed enum in database queries #50674

Merged
merged 2 commits into from
Mar 21, 2024
Merged

[11.x] Accept non-backed enum in database queries #50674

merged 2 commits into from
Mar 21, 2024

Conversation

gbalduzzi
Copy link
Contributor

This PR aims to implement non backed enums support for database queries, equivalent to the existing support for backed enums implemented in #39492

Non backed enums can be already used as eloquent attribute casting:

enum Status 
{
    case Active;
    case Archive;
}

class User extends Model 
{
  protected $casts = [
    'status' => Status::class,
  ];
}

The enumerative name property is used as the scalar value for Database storage.

$user = new User();
$user->status = Status::Active; // Stored as 'Active' in the database
$user->save();

However, using the enum in the query builder returns an error:

User::where('status', Status::Active)->get(); // ❌ ERROR: Object of class Status could not be converted to string

User::update([ 'status' => Status::Archive]); // ❌ ERROR: Object of class Status could not be converted to string

This PR enables this syntax, automatically casting each non-backed enumerative case to its name.

@taylorotwell taylorotwell merged commit 08772cf into laravel:11.x Mar 21, 2024
30 checks passed
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.

2 participants