EnikiBeniki
EnikiBeniki

Reputation: 981

Eloquent: How to get all polymorph models?

In this solution from official documentation in Laralvel/Eloquent (Polymorphic relations)

posts
    id - integer
    title - string
    body - text

videos
    id - integer
    title - string
    url - string

comments
    id - integer
    body - text
    commentable_id - integer
    commentable_type - string

We can retrive posts or videos: $post = App\Post::find(1) or $post = App\Post::all()

And we can get concrete comment

$comment = App\Comment::find(1);
$commentable = $comment->commentable;

In this case commentable method will return concrete Post or Video model.

But how to gel all comments as collection, where each of item will be Post or Video model? App\Comment::all() expectedly return records from comments table, this is not what we need.

Upvotes: 6

Views: 3333

Answers (1)

Gayan
Gayan

Reputation: 3704

the official doc also mentions how we should structure our classes

class Comment extends Model
{ 
    /** * Get all of the owning commentable models. */ 
    public function commentable()
    { 
        return $this->morphTo(); 
    }
} 

class Post extends Model 
{
    /** * Get all of  post's comments. */ 
    public function comments() 
    { 
        return $this->morphMany('App\Comment', 'commentable'); 
    } 
}


class Video extends Model 
{ 
    /** * Get all of the video's comments. */ 
    public function comments() 
    { 
        return $this->morphMany('App\Comment', 'commentable'); 
    } 
}

After doing so we can get comments of post like

$comments = Comments::with('commentable')->get();

$comments contains all the comments, in each comment you can retrieve $comment->commentable which contains either a Post or a Video.

Upvotes: 2

Related Questions