Skip to content

[12.x] Add enum functionality to morph map #56057

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

Closed
wants to merge 3 commits into from

Conversation

shaedrich
Copy link
Contributor

Enums are a powerful addition to the PHP language and with the enum_value() helper, working with them in Laravel is like a charm. This PR adds the ability to pass an enum to another of Laravel's features: Morph maps. So, instead of a non-exhaustive array, we can now add an enumerated mapping and benefit from better IDE support.

Examples

Define morph map

// Current functionality
Relation::morphMap([ 'App\Models\Post', 'App\Models\Video' ]); // results in ['posts' => 'App\Models\Post', 'videos' => 'App\Models\Video']
Relation::morphMap([ 'articles' => 'App\Models\Post', 'clips' => 'App\Models\Video' ]); // results in ['articles' => 'App\Models\Post', 'clips' => 'App\Models\Video']

// 🆕 functionality
enum MorphMap: string
{
    case Articles = 'App\Models\Post';
    case Clips = 'App\Models\Video';
}
Relation::morphMap(MorphMap::class); // results in MorphMap{Articles: 'App\Models\Post', Clips: 'App\Models\Video'}

Get morph alias

enum MorphMap: string
{
    case Articles = 'App\Models\Post';
    case Clips = 'App\Models\Video';
}
echo Relation::getMorphAlias(MorphMap::Articles); // results in 'Articles' (a little nonsensical)
echo Relation::getMorphAlias('App\Models\Post'); // results in 'Articles'

Get morphed model

enum MorphMap: string
{
    case Articles = 'App\Models\Post';
    case Clips = 'App\Models\Video';
}
echo Relation::getMorphedModel('Articles'); // results in App\Models\Post

@shaedrich
Copy link
Contributor Author

I'm not sure why static analysis / Types (pull_request) failed. I can't seem to find how this is related to my changes.

@shaedrich shaedrich changed the title Add enum functionality to morph map [12.x] Add enum functionality to morph map Jun 16, 2025
@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!

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