skip to Main Content

Help me please.

I’m trying to write a function where I get all the categories of my forum with the 3 most recently updated Topics in the given categories.

But according to the result, take(3) filters by id (where the id is not higher than 3), and I need to get the last 3 records.

public function index()
{
    $forums = Category::with(['posts' => function ($q){
    return $q->take(3)->get();
}])->get();
dd($forums);
}

2

Answers


  1. you should order your complete query by update_at descending, only after you can take the first 3.

    $q->orderBy('update_at', 'desc')->take(3)->get(); 
    

    Your Categories table seems to be a different table from posts, so when a post is created or updated you should also set update_at of its category to now.

    Login or Signup to reply.
  2. As far as I know you can not use take() or limit() inside with();


    EDIT: solution that was selected by mr.Sardov is to use package staudenmeir/eloquent-eager-limit.
    Link is provided below this answer.


    So for you need to do is by limit it from model relationship.

    For example:

    class Category extends Model {
    
    public function posts()
    {
        return $this->hasMany('AppModelsPost');
    }
    
    public function limitPosts()
    {
        return $this->hasMany('AppModelsPost')
          ->limit(3);
    }
    
    public function limitLatestPosts()
    {
        return $this->hasMany('AppModelsPost')
          ->orderBy('created_at', 'desc'). // or use ->latest()
          ->limit(3);
    }
    
    
    }
    

    And that use it like this:

    Category::query()
    ->with(['limitPosts' => function($query) { 
       $query->orderBy('created_at', 'desc'); // the last records
    }])
    ->where('id', '<=', 3) // id not higher than 3
    ->get();
    

    Or

    Category::query()
    ->with('limitLatestPosts')
    ->where('id', '<=', 3) // id not higher than 3
    ->get();
    

    Hope this can help you out.

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