skip to Main Content

I want to display only 3 news in each category to display the last 3 news that were added.

Class category:

class category extends Model
{
    use HasFactory;

    public function articles(){
        return $this->hasMany(Article::class)->limit(3)->orderBy('created_at', 'desc');
      }
  
}

Class Article:

class Article extends Model
{
    use HasFactory;

    public function category(){
        return $this->belongsTo(category::class);
    }
  
}

$categories = category::with('articles')->limit(3)->get();
$articles = Article::orderBy('created_at', 'desc')->get();

return response()->view('news.index', compact('categories','articles'));

2

Answers


  1. use whereHas

    $categories = category::whereHas('articles', function($query){
            return $query->orderBy('created_at', 'desc')->limit(3);
        })->get();
    
    return view('news.index', compact('categories'));
    
    Login or Signup to reply.
  2. By using latest()

    $categories = category::whereHas('articles', function($query){
            return $query->latest()->take(3);
        })->get();
    
    return view('news.index', compact('categories'));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search