Laravel - Relationships - Nested Eager Loading Morphto Relationships

If you would like to eager load a morphTo relationship, as well as nested relationships on the various entities that may be returned by that relationship, you may use the with method in combination with the morphTo relationship's morphWith method. To help illustrate this method, let's consider the following model:

    
    morphTo();
        }
    }
	

In this example, let's assume Event, Photo, and Post models may create ActivityFeed models. Additionally, let's assume that Event models belong to a Calendar model, Photo models are associated with Tag models, and Post models belong to an Author model.

Using these model definitions and relationships, we may retrieve ActivityFeed model instances and eager load all parentable models and their respective nested relationships:

    
    use Illuminate\Database\Eloquent\Relations\MorphTo;
    
    $activities = ActivityFeed::query()
        ->with(['parentable' => function (MorphTo $morphTo) {
            $morphTo->morphWith([
                Event::class => ['calendar'],
                Photo::class => ['tags'],
                Post::class => ['author'],
            ]);
        }])->get();