Laravel paginate method not working with map collection?
Here's a cleaner way to handle this.
$items = Item::with('product')->paginate(10)
->through(function($product){
$product->name = "Test";
return $product;
});
return response()->json(['items' => $items]);
Unlike map() which returns a brand new collection, through() applies to the current retrieved items rather than a brand new collection
As, given in Laravel docs, map()
method creates a new collection. To modify the values in the current collection, use transform()
method.
$items->getCollection()->transform(function ($product) {
$product->name = "Test";
return $product;
});
Also, since, paginator's items are a collection. You can use foreach
directly on $items
foreach ($items as $item)
{
$item->name = "Test";
}