Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lukeboy_2002's avatar

Count where active is true

I have a question how to count. Now I use this function:

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

This works only this count all posts in a category, this is not what I want. How can I count the posts where the post is active and the published date has been passed.

my two databases

        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->foreignId('category_id');
            $table->string('title');
            $table->string('slug')->unique();
            $table->text('excerpt');
            $table->text('body');
            $table->string('image')->nullable();
            $table->boolean('active')->nullable()->default(false);
            $table->timestamp('published_at')->nullable();
            $table->softDeletes();
            $table->timestamps();
        });

        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name')->unique();
            $table->string('slug')->unique();
            $table->timestamps();
        });

in Post model:

    public function author(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

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

in my category model

    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }
0 likes
5 replies
Snapey's avatar
Snapey
Best Answer
Level 122

Its something like this;

$categories = Category::withCount(['posts' => function($query) {
        $query
            ->where('active', true)
            ->where('published_at', '<', now());
    }])->get();

The withCount function can take a closure to filter the records

Please or to participate in this conversation.