skip to Main Content

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.

2

Answers


  1. 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();
    
    Login or Signup to reply.
  2. To retrieve only the latest ForumPost for each category, you can modify your query to use a subquery to select the latest post for each category. Here’s how you can do it in Laravel:

    use IlluminateDatabaseEloquentBuilder;
    $categories = ForumCategory::with(['posts' => function ($query) {
        $query->latest()->take(1); // Select only the latest post
    }])->get();
    
    // If you want to eager load the author relationship for the latest post
    $categories->load(['posts.author']);
    
    // Or you can use the following approach to eager load the author relationship directly in the initial query
    $categories = ForumCategory::with(['posts' => function ($query) {
        $query->with('author')->latest()->take(1); // Select only the latest post
    }])->get();
    

    Make sure you have proper indexes set up on your database tables to optimize the performance of this query, especially if you have a large dataset.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search