The paginate()
method is not available directly on the Illuminate\Database\Eloquent\Collection class. Instead, it is a method provided by the query builder (Illuminate\Database\Eloquent\Builder) or the model itself (Illuminate\Database\Eloquent\Model).
To merge two paginated collections and paginate the result, you can take a different approach:
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
$collection1 = Model1::paginate($perPage);
$collection2 = Model2::paginate($perPage);
$mergedCollection = $collection1->concat($collection2);
$currentPage = LengthAwarePaginator::resolveCurrentPage();
$perPage = 10; // Define the number of items per page for the final paginated result
$paginatedResult = new LengthAwarePaginator(
$mergedCollection->forPage($currentPage, $perPage),
$mergedCollection->count(),
$perPage,
$currentPage,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
]
);
// You can now use the $paginatedResult as needed
In this updated example, we use the concat()
method to merge the paginated collections. Then, we create a new instance of LengthAwarePaginator using the merged collection and the pagination information.
Make sure to import the necessary classes at the top of your file:
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
Now, you can use the $paginatedResult
as a paginated collection that combines the results of both collections. Adjust the $perPage
variable to set the desired number of items per page for the final result.