Get Nested Relationships From Morph Relationship – Laravel 8+
Have you used the morph relationship of laravel, then you might encounter this issue. Getting nested relationships from morph relations is a little bit difficult. Let’s go through it one by one.
Example 1: With Nested morph relation
I was working on a service selling platform, so here is the scenario. We need to find the transactions of a particular user with a transaction item that can be anything like Project Revision, Bonus Tips, or project itself.
$user->transactions()->with(['beneficiary', 'invoice', 'item' => function (MorphTo $morphTo) { $morphTo->morphWith([ Revision::class => [‘project’, ‘project.owner'], BonusTip::class => ['item' => function (MorphTo $morphTo2) { $morphTo2->morphWith([ Project::class => ['owner'] ]); }], Project::class => ['owner'] ]); }])
So, Illuminate\Database\Eloquent\Relations\MorphTo
is a useful solution for this problem, because it allows us to get nested relationships from morph relation in laravel.
Example 2: Load Nested morph relation
If you already have a collection and now want to get nested relationships from morph relationships then you can also use the following solution.
$activities = $transactions ->loadMorph(‘item’, [ Revision::class => [‘project’, ‘project.owner'], BonusTip::class => ['item' => function (MorphTo $morphTo) { $morphTo->morphWith([ Project::class => ['owner'] ]); }], Project::class => ['owner'] ]);
Cheers,
You will also like ajax file upload tutorial here.
We did it.