Skip to content

MorphTo fields won't work when morph type column uses php Enum with casts #5305

@andypooletrioteca

Description

@andypooletrioteca
  • Laravel Version: 9.48.0
  • Nova Version: v4.21.0 (Silver Surfer)
  • PHP Version: 8.2.1

Description:

MorphTo field doesn't seem to work well when a model has the type column casted as a php Enum.

Detailed steps to reproduce the issue on a fresh Nova installation:

Have an enum defining the models that can be contactable.

enum Contactable: string
{
    case PROVIDER => 'App\Models\Provider',
    case CUSTOMER => 'App\Models\Customer',
}

Have a polymorphic relation to these contactable models

class Contact extends Model
{
    protected $casts = [
        'contactable_type' => Contactable::class,
    ];
    
    public function contactable(): MorphTo
    {
        return $this->morphTo();
    }
}

Define a nova resource for this Model

class Contact extends Resource
{
    public static $model = 'App\Models\Contact';
    public function fields(NovaRequest $request)
    {
        return [
            MorphTo::make('Contact', 'contactable')->types(['App/Nova/Customer', 'App/Nova/Provider']),
        ];
    }
}

Then you get:

{
    "message": "Illegal offset type",
    "exception": "TypeError",
    "file": "/var/www/html/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Relation.php",
    "line": 475,
    "trace": [
        {
            "file": "/var/www/html/vendor/laravel/nova/src/Fields/MorphTo.php",
            "line": 276,
            "function": "getMorphedModel",
            "class": "Illuminate\\Database\\Eloquent\\Relations\\Relation",
            "type": "::"
        },
        ...

I guess contactable_type is not expected to be casted as an Enum... but why not?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions