The issue you're encountering is due to the fact that the groupBy method is being called on a LengthAwarePaginator instance returned by the paginate method, which does not have a groupBy method. The groupBy method is available on collections, not on paginated results directly.
To achieve pagination with grouped results, you'll need to first get the collection, then group, and finally manually create a paginator for the grouped collection. Here's how you can do it:
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
// Get your transactions
$transactions = Transaction::latest()->get();
// Group the transactions by date
$groupedTransactions = $transactions->groupBy(function ($item) {
return Carbon::parse($item->getRawOriginal('created_at'))->format('M d, Y');
});
// Define how many items we want to be visible in each page
$perPage = 10;
// Get current page form url e.x. &page=1
$page = Paginator::resolveCurrentPage();
// Slice the collection to get the items to display in current page
$currentPageItems = $groupedTransactions->slice(($page - 1) * $perPage, $perPage)->all();
// Create our paginator and pass it to the view
$paginatedItems = new LengthAwarePaginator($currentPageItems, count($groupedTransactions), $perPage, $page, [
'path' => Paginator::resolveCurrentPath(),
]);
return view('your_view', ['collections' => $paginatedItems]);
In this solution, we first retrieve all the transactions and then apply the groupBy method. After grouping, we manually create a paginator instance using LengthAwarePaginator. This allows us to paginate the grouped collection.
Remember to replace 'your_view' with the actual view you're using and pass the $paginatedItems to your view, where you can loop through the items and use the links() method to render the pagination links.
Keep in mind that this approach can be memory-intensive if you're working with a very large dataset, as it requires loading all transactions into memory to perform the grouping. If your dataset is large, consider using a more database-centric approach to handle grouping and pagination, possibly with raw queries or advanced Eloquent techniques.