Reputation: 25
I have these as a sample of records 2016/01/13, 2016/01/15, 2016/01/25, 2015/01/14, 2015/01/17, 2015/01/28 and so on.
Any suggestions on how to only count (yyyy) where the month of January appears so that I get 2.(2016,2015)
$stocks = DB::table('inventories')
->select('inventories.*',DB::raw('count(*) as count,date_sold'))
->whereMonth('complete_sold','=', Carbon::today()->month)
->groupBy('inventories.drug_id')
->get();
Upvotes: 0
Views: 317
Reputation: 9465
Option 1: If you only want count
$stocks = DB::table('inventories')
->whereMonth('complete_sold','=', Carbon::today()->month)
->distinct()->count("year(complete_sold)");
Option 2: If you need the records of the years
$stocks = DB::table('inventories')
->whereMonth('complete_sold','=', Carbon::today()->month)
->select(DB::raw("year(complete_sold)"))
->groupBy(DB::raw("year(complete_sold)"))->get();
Upvotes: 0
Reputation: 9942
Option 1:
If you only need the count number and not the records from the database do this:
$stocks = DB::table('inventories')
->whereMonth('complete_sold','=', Carbon::today()->month)
->groupBy('inventories.drug_id')
->count();
This way $stock will equal to number of records found (example: 2
). The count will be performed on SQL level (example: SELECT count(*) ....
).
Option 2:
If you will need the records later on, you could do it like this:
$stocks = DB::table('inventories')
->whereMonth('complete_sold','=', Carbon::today()->month)
->groupBy('inventories.drug_id')
->get();
$stockCount = $stock->count();
This way $stock
will have the results of the query saved (the records from the database). And $stockCount
will be a number of records. The count will be performed on collection (php).
Upvotes: 1