Home > Software design >  Sort a group, depending on key
Sort a group, depending on key

Time:12-29

I have a seller list, who are paying service charge. I am listing the service charge according the year. Suppose seller A,C,D paid service charge in 2021, Seller B,E,F in 2022. I want to group them and show in list. Till grouping its okay. The problem I am facing is, The record group is showing 2021 first then 2022, it's showing the group in ascending order. But I want it in descending order.

Controller

public function service(){
   $infos = ServiceCharge::all()->groupBy('year');
   $sellerInfo = Seller_info::orderBy('id','DESC')->get();
   return view('Backend.pages.account.service',compact('infos','sellerInfo'));
}

If I use this

$infos = ServiceCharge::orderBy('year','DESC')->groupBy('year')->get();
dd($infos);

It shows only one value, The first entered value

but without groupBy

$infos = ServiceCharge::orderBy('year','DESC')->get();
dd($infos);

it shows all the value. I entered 2 value. This is my inserted data formation How can I print this in latest year order?

CodePudding user response:

You should use the get method instead of all:

$infos = ServiceCharge::groupBy('year')->orderBy('year','DESC')->get();

CodePudding user response:

$infos = ServiceCharge::orderBy('year','DESC')->get()->unique('year');

or

 $infos = ServiceCharge::orderBy('year','DESC')->groupBy('year')->get();
  • Related