Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel get all categories with posts count

Hi, I'm trying to get Array contain all Categories with Number of Posts in each category: Ex:

[
{id: 1, name: "category1", posts: 15 },
{id: 2, name: "category2", posts: 33 },
{id: 3, name: "category3", posts: 27 }
]

Details:

  • Posts Table
public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->string('slug')->unique();
        $table->string('title');
        $table->string('image');
        $table->text('description');
        $table->integer('category_id')->unsigned();;
        $table->longText('content');
        $table->boolean('published')->default(0);
        $table->timestamps();
    });
}
  • Categories Table
public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name')->unique();
        $table->timestamps();
    });
}
  • Posts Model
public function category()
{
  return $this->belongsTo('App\Models\Category');
}
  • Category Model
public function posts()
{
  return $this->hasMany('App\Models\Post');
}
  • Categories Controller
public function index()
{
  $Categories  = Category::with('posts')->get();
  return response()->json($Categories);
}

but the this function return posts with all filed, is way to count them and add number as param in array ?

like image 712
AiAbdrahim Avatar asked Feb 20 '20 18:02

AiAbdrahim


1 Answers

You can use withCount

$categories = Category::withCount('posts')->get(); 

then you can loop trough $categories and access to

$category->posts_count 

on each category .

like image 105
porloscerros Ψ Avatar answered Oct 23 '22 03:10

porloscerros Ψ