Get last item of an array

Use array_key_last() to get last key. Do not use end(), if the item contain objects, end() will cause error.

$last_index = array_key_last($subcat->products);
$last = $subcat->products[$last_index];
$last->cat_product_count = $count;
$subcat->products[$last_index] = $last;

Use Laravel Collection Object

$arr = collect([]);

$last = $subcat->products->pop();
$last->cat_product_count = $count;
$subcat->products->push($last);