Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

SNaRe's avatar
Level 7

How to use Laravel Collection groupBy along with Query Pagination? Ask Question

I love using Laravel's groupBy function https://laravel.com/docs/5.6/collections#method-groupby

However, I cannot use it with paginate(x) function since it return a limited number of results. Groupby of SQL Query and Laravel Collections's GroupBy is totally different. If I use groupby in my query it doesn't give me what I want. For instance I just want to type and I got all I want.

$notifications = $notifications->groupBy('order_id');

For example this is my query

    $notifications = DB::table('sent_notifications as a')
        ->join('sent_notification_results as b', 'a.sent_notification_result_id', '=', 'b.sent_notification_result_id')
        ->join('orders as c', 'c.order_id', '=', 'a.order_id')
        ->join('sellers as d', 'c.seller_id', '=', 'd.seller_id')
        ->join('companies as e', 'd.company_id', '=', 'e.company_id')
        ->join('notification_templates as f', 'f.notification_template_id', '=', 'a.notification_template_id')
        ->join('notification_types as g', 'g.notification_type_id', '=', 'f.notification_type_id')
        ->join('default_notification_templates as h', 'h.default_notification_template_id', '=', 'f.default_notification_template_id')
        ->where('e.company_id', $company_id)
        ->select('*')
        ->orderBy('a.created_at','DESC')
        ->paginate(20);
    $pagination_links = $notifications->links();

How can I use Collection's groupby method along with pagination?

0 likes
0 replies

Please or to participate in this conversation.