'Laravel WhereHas only the latest record on the HasMany Relationship

I have Items table that has relation to Histories table.

I want to get count of items that has only latest history.status

I still can't get the exact same count result because its always count all of the histories not the latest one

Here is my code:

create_items_table.php

Schema::create('items', function (Blueprint $table) {
        $table->id();
        $table->string('code');
        $table->string('name');
        $table->longText('description')->nullable();
        $table->longText('picture')->nullable();
        $table->timestamps();
    });

create_histories_table.php

$table->foreignId('item_id')->constrained();
$table->string('status')->nullable();
$table->longText('description')->nullable();
$table->dateTime('date')->nullable();

model of Item.php

public function histories(){
        return $this->hasMany(History::class);
    }
public function latestHistory(){
        return $this->hasOne(History::class)->latest();
    }

model of History.php

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

MyController.php

 $items_status['good'] = Item::with('latestHistory')->whereHas('latestHistory', function ($q) {
            $q->where('status', 'good');
        })->count();

 $items_status['broken'] = Item::with('latestHistory')->whereHas('latestHistory', function ($q) {
            $q->where('status', 'broken');
        })->count();

dd($items_status);


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source