Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Conversation

gdebrauwer
Copy link
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.

None yet

2 participants