Steve
Steve

Reputation: 1672

Building polymorphic relations in laravel 5.2

Answer have comments, comments have votes.
Answer have votes.

votes table:
id  user_id  vote  votable_id  votable_type
1     1       5     1          Comment
2     1       6     1          Post
...

Post Model:

 public function comments()
    {
        return $this->hasMany('App\Comment','post_id','id'); 
    }

   public function votes()
    {
        return $this->morphMany('App\Vote', 'votable');
    }

Comment Model:

public function votes()
{
    return $this->morphMany('App\Vote', 'votable');
}

public function post()
{
    return $this->belongsTo('App\Post','post_id','id'); 
}

Vote Model:

 public function votable()
    {
        return $this->morphTo();
    }

I am getting all the posts and their comments but not votes of posts and comments.

$posts=Post::all();
foreach($posts as $post)
{
     echo "<pre>"; print_r($post->post);    
     foreach($post->comments as $comment)
     {
        echo "<pre>"; print_r($comment->comment_body);
        foreach($comment->votes as $vote)
        {
            echo "<pre>"; print_r($vote->vote);
        }               
     }

    foreach($post->votes as $vote)
    {
        echo "<pre>"; print_r($vote->vote);
    }
}

print_r($post->votes); and print_r($comment->votes); doesnot show any relations with vote.

Upvotes: 1

Views: 69

Answers (1)

prateekkathal
prateekkathal

Reputation: 3572

Please use App\Comment and App\Post instead of Comment or Post in the votable column.

Laravel 4.2 used to keep only the names of Models, but Laravel 5.2 stores them with the namespace now.

Let me know if there are any more doubts :)

-- Edit

As asked by @jaysingkar in the comments, I am adding the code for doing morphMap for this question.

Create your own service provider from the following command

php artisan make:provider RelationServiceProvider

Then, create put this after the namespace

use Illuminate\Database\Eloquent\Relations\Relation;

and then add this to the boot() method

Relation::morphMap([
  'Posts' => App\Post::class,
  'Comments' => App\Comment::class,
]);

Hope it helps! :)

Upvotes: 2

Related Questions