1

I working on an app that involves grouping selected rows by month. How do I go about it?

  $data = Medicals::where("patient_referral.referred_by", "like", "%" .  $searchitem . "%")
        ->leftJoin("patients", "medicals.patients_id", "=", "patients.id")
        ->join("patient_referral", "medicals.trx_id", "=", "patient_referral.trx_id")
        ->join("tests", "medicals.tests_id", "=", "tests.id")
        ->groupBy(function (Medicals $item) {
            return $item->created_at->format('Y-m');
        })
        ->get();

This is the error am getting

ErrorException stripos() expects parameter 1 to be string, object given

mychuks
  • 53
  • 1
  • 8
  • What is the problem you are having, does your query not work as you expect? You need to add some more information to your question. If you get an error, add it to your question. – Tony Jan 26 '21 at 09:05
  • does this help: https://stackoverflow.com/questions/40529355/laravel-eloquent-group-by-month-year – Gert B. Jan 26 '21 at 09:20

2 Answers2

2

The way you are calling groupBy is for Collections, not a query. You need to move that groupBy after the get so you are trying to group the resulting Collection.

    ...
    ->get()
    ->groupBy(function ($item) {
        return $item->created_at->format('Y-m');
    });
lagbox
  • 48,571
  • 8
  • 72
  • 83
1

You can use a raw query in a groupBy to execute it in the database:

$data = Medicals::where("patient_referral.referred_by", "like", "%" .  $searchitem . "%")
        ...
        ->groupBy(DB::raw('DATE_FORMAT(medicals.created_at, "%Y-%m")'))
        ->get();
Tony
  • 9,672
  • 3
  • 47
  • 75