Laravel using Sum and Groupby

Theodory Faustine picture Theodory Faustine · Aug 27, 2018 · Viewed 7.7k times · Source

I would like to fetch sum of quantity in each month, so that I can display on bar chart quantities against month

This is what I thought but didn't workout

 $data1 = Borrow::groupBy(function($d) {
 return Carbon::parse($d->created_at)->format('m')->sum('quantity');
 })->get();

My table structure

Schema::create('borrows', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('member_id');
        $table->integer('book_id');
        $table->integer('quantity');
        $table->integer('status')->default(0);
        $table->timestamps();
    });

Answer

Erubiel picture Erubiel · Aug 27, 2018

that a collection group by not an eloquent groupby

if you want to do it with eloquent, gotta:

 $data1 = Borrow::selectRaw('SUM(quantity) as qt, MONTH(created_at) as borrowMonth')
      ->groupBy('borrowMonth')->get();

if you want to do it with the collection groupBy method, you should first do the get, then the groupBy.

As in, though im not sure what you're trying to accomplish with what you do inside the callback..

 $data1 = Borrow::get()->groupBy(function($d) {
 return Carbon::parse($d->created_at)->format('m')->sum('quantity');
 });