Search code examples
laraveleloquent

Laravel has many through latest model


I'm using laravel 10.

I have following structure in DB

forum_categories
  id

forum_threads
  id
  forum_category_id

forum_posts
  id
  forum_thread_id

My goal is, using the eloquent get all categories with latest ForumPost model.

In model ForumCategory i have following method:

public function posts(): HasManyThrough
    {
        return $this->hasManyThrough( ForumPost::class, ForumThread::class);
    }

And my query:

$categories =  ForumCategory::with(['posts' => function ($q) {
            $q->with('author')->latest();
        }])->get();

It works fine but it loads all ForumPosts not only the last one.

So, how to retrieve only the last one ForumPost for each category?

Thank you.


Solution

  • you can define another relationship hasOneThrough in your ForumCategory to fetch the latest post like,

    public function latestPost()
    {
        return $this->hasOneThrough(ForumPost::class, ForumThread::class)->latest('id');
    }
    

    and then,

    $categories = ForumCategory::with('latestPost.author')->get();