Support the ongoing development of Laravel.io →
Database Eloquent

these are my relations..

User model

 public function posts()
  {
    return $this->hasMany('Post');
  } 

Post model

   public function user()
   {
     return $this->belongsTo('User');
    }
     public function replies()
      {
         return $this->hasMany('Reply');
       }

Reply Model

      public function post()
      {
         return $this->belongsTo('Post');
       }

And schema is

users: id name

post:id user_id

comments:id post_id

I want to display the posts that has comments using

          $user = User::find(Auth::user()->id);
          $templatedata = $user->posts()->replies->get()

but its giving call to undefined method.. Please help me..!!

Last updated 3 years ago.
0

Try this:

$templatedata = $user->posts()->with('replies')->get();

The $templatedata will be a Collection of Post objects each having a property ->replies which will contain a Collection of Reply objects.

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.