Laravel group by date to month only and get count

2019-06-24 14:13发布

问题:

I have transactions table :

My table architecture :

id | item_name | quantity | created_at

I have try many method but its not work (link : Laravel Eloquent get results grouped by days.

I want to display it like this :

Example :

Qty : xxx Month : July

Qty : xxx Month : October

Qty : xxx Month : November

How to convert from created_at column to month only grouping and display it as Word instead of numbers and then get count of grouping quantity in that month?

Thank you

回答1:

    $data= Transaction::select('id', 'item_name','quantity', 'created_at')
            ->get()
            ->groupBy(function($val) {
            return Carbon::parse($val->created_at)->format('m');
     });


回答2:

In case you don't want to use carbon

$data= Transaction::get()
    ->groupBy(function($item) {
    return $item->created_at->month;
});


回答3:

use eloquent date function to find only the date, you can use month to get the month or year to get only the year.

For example:

public function salesmonthly(Request $request){

    $monthlysales=DB::table('tbl_invs')
     ->select(DB::raw('sum(total) as total'),DB::raw('date(created_at) as dates'))
     ->groupBy('dates')
     ->orderBy('dates','desc')
    ->get();


    // dd($monthlysales);
    return view('reports.monthlysales', compact('monthlysales'));
}


标签: laravel-5