Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel paginate method not working with map collection?

Tags:

php

laravel

$items = Item::with('product')->paginate(10);

    $items = $items->map(function($product){
          $product->name = "Test";
          return $product; 
    });

    return response()->json(['items' => $items]);

In my view blade on console paginate objects not showed?

like image 723
Manchester Avatar asked Aug 27 '17 10:08

Manchester


4 Answers

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";
}
like image 136
jaysingkar Avatar answered Oct 22 '22 23:10

jaysingkar


An easy solution would be to just use tap() like so:

return tap(Item::with('product')->paginate(10))->map(...);

The tap() helper always returns its argument, so you can call any function you like and still return the paginator instance. This is often used in instances like return tap($user)->save(), where the save function returns a boolean but you still want to return the $user object.

like image 42
Flame Avatar answered Oct 22 '22 22:10

Flame


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
like image 25
Mark Tems Avatar answered Oct 22 '22 22:10

Mark Tems


You should save the data in a collection, work on them, inject them back, something like this:

$page = Input::get('page', 1);
$data = Item::with('product')->getByPage($page, 10);
$tempItems = $data->items;

$tempItems = $tempItems->map(function($product){
      $product->name = "Test";
      return $product; 
});


$objects = Paginator::make($tempItems, $data->totalItems, 10);
like image 1
Bara' ayyash Avatar answered Oct 22 '22 21:10

Bara' ayyash