0
votes

How can I convert the code below to a single query in eloquent ?

The table has the following columns ( id (primary index) - sku - serial_number - status - created_at - updated_at)

The aim is to retrieve the latest status 'latest record' of each product that shares the same SKU.

// get all the products that shares the same sku number
$list_of_products_status = Product_status::where('sku', 'sku-number')
    ->get();


$list_unique_serials = $list_of_products_status->pluck('serial_number')->toArray();

$products= collect([]);
foreach ($list_unique_serials as $serial)
{
// get the latest status of each product
    $product = Product_status::where('serial_number', $serial)
        ->latest()->first();
    $products[] = $product;
}
If you tell more clearly the appearance of the tables - Akbarali
Yes I updated the answer. - Marcos DaSilva
Try this $list_of_products_status = Product_status::query()->where('sku', 'sku-number')->latest()->groupBy('serial_number')->get(); - Akbarali
I have the error column "product_status.id" must appear in the GROUP BY clause or be used in an aggregate function - Marcos DaSilva