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