Search code examples
phplaraveleloquentlaravel-7eloquent-relationship

Retrieve records on relationship laravel


I need to show the posts that has been published in a topic when a User is logged. A user can follow many topics. 1 topic has many posts and 1 topic has many Users 'enrolled' via the pivot table 'topic_user'

I'd like to know the query for this..

I have this 4 models:

1 - normal user

then:

class Post extends Model
{
    use SoftDeletes;
    //
    protected $fillable = ['title','content', 'creator_id','topic_id','flag_id','deleted_at',"created_at"];
    
    public function topic(){
        return $this->belongsTo(Topic::class);
    }
}
class Topic extends Model
{
    use SoftDeletes;
    protected $fillable = ['name','description','active','creator_id','nsfw','type_id','formal_name','theme','joined_community'];

    public function posts(){
        return $this->hasMany(Post::class);
    }
    public function enrolled(){
        return $this->belongsToMany(User::class,'topic_user');
    }
}
class UserOnTopic extends Model
{
    protected $fillable = ["user_id","topic_id"];
    protected $table = "topic_user";
}


Solution

  • You already have set up your relations. So, you can query users with topics and posts:

    $user_posts = User::with('topics', 'topics.posts')->first();
    

    This line of code returns the first user, with all posts that belongs to the topics he follows.

    You can display his posts in your frontend using something like this:

    <ul>
    @foreach($user_posts->topics as $topic)
        @foreach($topic->posts as $post)
            <li>{{ $post->id }}</li>
        @endforeach
    @endforeach
    </ul>