Laravel Bring data of the model grouped by months

1

Hello, I have the following table in the DB

Fruta 

id | name | precio | fecha_compra

I would like to bring the total price of all purchased fruits grouped by months using eloquent or querybuuilder

the result that is but is the following:

{
   "Enero" : "338$",
   "Febrero" : "555$",
    ...
    ...
    ...
   "Diciembre" : "100$"
}
    
asked by kevin au tam 27.06.2018 в 23:06
source

2 answers

1

Solved

$frutas= Fruta::select(
            DB::raw('sum(precio) as sums'),
            DB::raw("DATE_FORMAT(created_at,'%M %Y') as months")
        )
            ->groupBy('months')
            ->get();
    
answered by 28.06.2018 в 00:14
0

I propose the following solution with Fluent the QueryBuilder of Laravel

$data = Fruta::
        select(DB::raw("name, mes, SUM(precio) as count"))
        ->groupBy("mes")
        ->orderBy('mes', 'DESC')
        ->get();
    return $data;
  

It should be noted that since we are going to use Fluent, in the upper part   you have to import the DB Facade namespace; as follows

use DB;
    
answered by 27.06.2018 в 23:18