Search code examples
collectionslaravelpaginator

laravel 4 - add to paginated collection


I want to manually add items to a collection - works fine with a collection returned from get(), but fails when collection returned from paginate(), e.g.

$rows = $query->get();
$rows->add(new Model());

working fine

$rows = $query->paginate(10);
$rows->add(new Model());

give this error: Paginator.php 502: call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Support\Collection' does not have a method 'add'

I guess paginate is returning a paginator object rather than an eloquent collection, just wondering if there is a way to append to this?

Thanks :-)


Solution

  • Laravel 5:

    $rows->getCollection()->add(new Model());
    

    Laravel 4:

    add is Eloquent\Collection method and you can't use it on the Paginator which relies on Support\Collection.

    Use this workaround if you need to append items:

    $items = $rows->getItems();
    $items[] = new Model();
    $rows->setItems($items);