Home > Software engineering >  I want to display only 3 news in each category to display the last 3 news that were added
I want to display only 3 news in each category to display the last 3 news that were added

Time:09-19

class category extends Model
{
   use HasFactory;

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


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'));

CodePudding user response:

use whereHas

$categories = category::whereHas('articles', function($query){
        return $query->orderBy('created_at', 'desc')->limit(3);
    })->get();

return view('news.index', compact('categories'));
  • Related