2

I have a variable that is a pagination object

$pagination

I am changing things inside of it using transform

$pagination->getCollection()->transform(function ($item, $key) use(&$data, &$pagination) {
    $item->foo = 'bar';
}

I want to remove an item from the pagination if it meets a certain condition. I don't want it removed until after I've been able to use the data. Following is an example.

$pagination->getCollection()->transform(function ($item, $key) use(&$data, &$pagination) {
    $data[] = $item->foo;
    if ($item->foo === 'bar') {
        $item->remove();
    }
}

I've also tried using $pagination->getCollection()->forget($key); inside of the transform

$pagination->getCollection()->transform(function ($item, $key) use(&$data, &$pagination) {
    $data[] = $item->foo;
    if ($item->foo === 'bar') {
        $pagination->getCollection()->forget($key);
    }
}

That's from this question.

How to unset (remove) a collection element after fetching it?

I'm guessing the fact I'm dealing with a pagination may be making these answers not apply to my situation.

Tridev Shrestha
  • 447
  • 7
  • 21
Goose
  • 4,764
  • 5
  • 45
  • 84

1 Answers1

6

Doing a separate collection of pagination with filter() allows removing items from the pagination based on complex conditions. I return false in the transform and then simply target it in the filter.

$pagination = $pagination->getCollection()->filter(function ($item) {
    return $item;
});

Edit: This actually removed the pagination properties, so I've recreated the pagination afterwards like so

// Remove already merged rows
$itemsTransformed = $pagination->getCollection()->filter(function ($item) {
  return $item;
});

// Recreate because filter removed pagination properties
$itemsTransformedAndPaginated = new \Illuminate\Pagination\LengthAwarePaginator(
  $itemsTransformed,
  $pagination->total(),
  $pagination->perPage(),
  $pagination->currentPage(), [
    'path' => \Request::url(),
    'query' => [
      'page' => $pagination->currentPage()
    ]
  ]
);
Goose
  • 4,764
  • 5
  • 45
  • 84
  • 1
    Thanks for your useful answer, the only thing that has to be noted is that when setting pagination properties, use `count($itemsTransformed)` instead of `$pagination->total()`, otherwise the old total count (total count of the not filtered list) would be displayed. – Mostafa Arian Nejad Jan 25 '21 at 20:28