Skip to content

[7.x] Add 'loadMorph' and 'loadMorphCount' on Eloquent Model#32760

Merged
taylorotwell merged 3 commits intolaravel:7.xfrom
gdebrauwer:loadmorph-and-loadmorphcount-on-eloquent-model
May 11, 2020
Merged

[7.x] Add 'loadMorph' and 'loadMorphCount' on Eloquent Model#32760
taylorotwell merged 3 commits intolaravel:7.xfrom
gdebrauwer:loadmorph-and-loadmorphcount-on-eloquent-model

Conversation

@gdebrauwer
Copy link
Copy Markdown
Contributor

The loadMorph method already exists on Eloquent collection since v5.6 (#23626).
I recently added the loadMorphCount method to the Eloquent collection (#32739).

If you have a collection of Eloquent models, these methods work very well. But what if you only have one model? You have to write this kind of if-statements:

$comment = Comment::first();

if ($comment->commentable instanceof Post) {
    $comment->commentable->load('likes');
    // or
    $comment->commentable->loadCount('likes');
} elseif ($comment->commentable instance Video) {
    $comment->commentable->load('views');
    // or
    $comment->commentable->loadCount('views');
}

By adding loadMorph and loadMorphCount methods to the Eloquent Model, this becomes a lot more elegant:

$comment = Comment::first()

$comment->loadMorph('commentable', [
   Post::class => ['likes'],
   Video::class => ['views'],
]);

$comment->loadMorphCount('commentable', [
   Post::class => ['likes'],
   Video::class => ['views'],
]);

@taylorotwell taylorotwell merged commit dcf2d33 into laravel:7.x May 11, 2020
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