teddles's avatar

MorphMany Nova field on edit form

Is there a way to interact with MorphMany relationships on the edit form?

I am looking for repeater-like functionality, but with a MorphMany instead of a HasMany. MorphMany's problem is that it appears on view, instead of edit. Is this possible?

0 likes
1 reply
LaryAI's avatar
Level 58

To interact with MorphMany relationships on the edit form in Laravel Nova, you can use a combination of custom fields and resources to achieve a repeater-like functionality. Here's a step-by-step solution:

  1. Create a Nova Resource for the MorphMany Relationship:

    First, ensure you have a Nova resource for the related model. This will allow you to manage the related entries directly from the parent resource.

  2. Use the MorphMany Field in the Parent Resource:

    In your parent Nova resource, you can define a MorphMany field. This will allow you to manage the related entries directly from the parent resource's detail view.

    use Laravel\Nova\Fields\MorphMany;
    
    public function fields(Request $request)
    {
        return [
            // Other fields...
    
            MorphMany::make('Related Items', 'relatedItems', RelatedItemResource::class),
        ];
    }
    

    Replace relatedItems with the name of your relationship method, and RelatedItemResource with the Nova resource class for the related model.

  3. Customizing the Edit Form:

    To achieve a repeater-like functionality, you might need to create a custom Nova field or use an existing package that provides repeater functionality. Unfortunately, Nova does not natively support inline editing of MorphMany relationships on the edit form.

    However, you can use packages like nova-inline-morph-to or nova-repeater-field to enhance the editing experience. These packages allow you to manage related entries more dynamically.

  4. Handling the Relationship Logic:

    Ensure that your models are set up correctly to handle the MorphMany relationship. In your parent model, define the relationship like so:

    public function relatedItems()
    {
        return $this->morphMany(RelatedItem::class, 'morphable');
    }
    

    And in your related model, ensure you have the inverse relationship defined:

    public function morphable()
    {
        return $this->morphTo();
    }
    

By following these steps, you can manage MorphMany relationships in a more interactive way on the edit form in Laravel Nova. If you need more advanced functionality, consider extending Nova with custom fields or leveraging community packages.

Please or to participate in this conversation.