0

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?

Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109
SNaRe
  • 1,997
  • 6
  • 32
  • 68

1 Answers1

0

I worked on a project with a similar issue and came up with this solution.

public function index(Request $request)
{
    $posts = Post::all()
        ->paginate($request->get('per_page', 25));

    $grouped_by_date = $posts->mapToGroups(function ($post) {
        return [$post->published_date => $post];
    });
    $posts_by_date = $posts->setCollection($grouped_by_date);

    return view('posts.index', compact('posts_by_date'));
}
David
  • 168
  • 2
  • 5