Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

fbc's avatar
Level 2

How do you query this months records with epoch time?

I need to SUM all the values for a given month. The beginning of that process is to query the records for that month. I'm pretty sure I'm going to need Carbon to convert the UNIX timestamp to something I can filter from. So that is the route I was going with this. There might be a better way to do this. So any suggestion is appreciated.

I'm trying to do something like this:

        $this_months_values = (new $propdash->custommenuitems->monthly_real_time_feed)::whereMonth(Carbon::createFromTimestamp($time)->month, '=', date('m'))->orderBy('time', 'desc')->take(30)->get();

        $one_month_ago_values = (new $propdash->custommenuitems->monthly_real_time_feed)::whereMonth(Carbon::createFromTimestamp($time)->month, '=', (date('m')-1))->orderBy('time', 'desc')->take(30)->get();

        $two_month_ago_values = (new $propdash->custommenuitems->monthly_real_time_feed)::whereMonth(Carbon::createFromTimestamp($time)->month, '=', (date('m')-2))->orderBy('time', 'desc')->take(30)->get();

dd results of $this_months_values is:

Collection {#9512 ▼
  #items: array:2 [▼
    0 => Feed115 {#9511 ▼
      #connection: "emoncms"
      #table: "feed_115"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:2 [▼
        "time" => 1552716000
        "data" => 222.314
      ]
      #original: array:2 [▼
        "time" => 1552716000
        "data" => 222.314
      ]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
      #guarded: array:1 [▶]
    }
    1 => Feed115 {#9510 ▼
      #connection: "emoncms"
      #table: "feed_115"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:2 [▼
        "time" => 1552629600
        "data" => 405.903
      ]
      #original: array:2 [▼
        "time" => 1552629600
        "data" => 405.903
      ]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
      #guarded: array:1 [▶]
    }
  ]
}
0 likes
4 replies
Cronix's avatar

You're close. Use the sum() method to total that column for you. https://laravel.com/docs/5.8/queries#aggregates

You probably don't want a limit() on those results? How would taking only 30 results give you an accurate total?

You will probably also want to do a whereYear(), otherwise you're just totaling a single month for all years in the db. If you search for just September, you'll get results for September 2017, September 2018 and 2019 in the result set assuming you have data for other years.

If you only want the totals, then orderBy() is not really doing anything. It will make the query take longer though if that column isn't indexed.

date('m')-2

So if the month is january (month 1), you'll end up with -1 for the month. date('m') does give you the correct current numerical month, but subtracting from it doesn't guarantee you'll land on a real month. You need date math for that, so it wraps at 12 months. Subtracting 2 months from Jan should give you November of the previous year.

fbc's avatar
Level 2

@CRONIX - SUM is awesome!!! I will try to use it!!

I figured 30 because of 30 days in a month, but there are a few months with 31 days, so maybe all() is more appropriate here.

Yes I'm trying to show the cumulative values for the previous year by month. So I need to sum up all values for an entire month for that last 12 months.

You are correct about the

date('m')-2

deal. I would have to write a routine to wrap the negative numbers that will be another adventure and another post for suggestions.

The idea here is to create a chart that show the cumulative value SUM() for the current month, and 11 previous months.

I will keep working on this until I get it right. I know there are helpers to query current and previous months however they are not setup to deal with EPOCH time.

fbc's avatar
Level 2

@CRONIX - Ok I think I figured out the best way to go about this. No I just need to figure out is how to do a ->where('time'(in unix timestamp),$date->copy()->format('m')) something like:

        $this_months_values = (new $propdash->custommenuitems->monthly_real_time_feed)::where('time',$date->copy()->format('m'))->sum('data');

So far i'm down to this:

        $date = Carbon::today();

        /* Yearly Realtime Consumption data feed */
        $this_months_values = (new $propdash->custommenuitems->monthly_real_time_feed)::where('time',$date->copy()->format('m'))->sum('data');
        $one_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');
        $two_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');
        $three_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');
        $four_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');
        $five_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');
        $six_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');
        $seven_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');
        $eight_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');
        $nine_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');
        $ten_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');
        $eleven_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::sum('data');

        /* Create the chart */
        $yearly_consumption_chart = new HighCharts;
        $yearly_consumption_chart->labels([
            $date->copy()->subMonths(11)->format('F'),
            $date->copy()->subMonths(10)->format('F'),
            $date->copy()->subMonths(9)->format('F'),
            $date->copy()->subMonths(8)->format('F'),
            $date->copy()->subMonths(7)->format('F'),
            $date->copy()->subMonths(6)->format('F'),
            $date->copy()->subMonths(5)->format('F'),
            $date->copy()->subMonths(4)->format('F'),
            $date->copy()->subMonths(3)->format('F'),
            $date->copy()->subMonths(2)->format('F'),
            $date->copy()->subMonths(1)->format('F'),
            $date->copy()->format('F')]);
        $yearly_consumption_chart->dataset('kWh', 'line', [$eleven_month_agos_values,
            $ten_month_agos_values,$nine_month_agos_values,$eight_month_agos_values,
            $seven_month_agos_values,$six_month_agos_values,$five_month_agos_values,$four_month_agos_values,
            $three_month_agos_values,$two_month_agos_values,$one_month_agos_values,$this_months_values]);

fbc's avatar
fbc
OP
Best Answer
Level 2

I ended up solving it like this:

        $date = Carbon::today();

        /* Yearly Realtime Consumption data feed */
        $startthis = Carbon::now()->startOfMonth()->timestamp;
        $endthis = Carbon::now()->endOfMonth()->timestamp;
        $startone = Carbon::now()->subMonths(1)->startOfMonth()->timestamp;
        $endone = Carbon::now()->subMonths(1)->endOfMonth()->timestamp;
        $starttwo = Carbon::now()->subMonths(2)->startOfMonth()->timestamp;
        $endtwo = Carbon::now()->subMonths(2)->endOfMonth()->timestamp;
        $startthree = Carbon::now()->subMonths(3)->startOfMonth()->timestamp;
        $endthree = Carbon::now()->subMonths(3)->endOfMonth()->timestamp;
        $startfour = Carbon::now()->subMonths(4)->startOfMonth()->timestamp;
        $endfour = Carbon::now()->subMonths(4)->endOfMonth()->timestamp;
        $startfive = Carbon::now()->subMonths(5)->startOfMonth()->timestamp;
        $endfive = Carbon::now()->subMonths(5)->endOfMonth()->timestamp;
        $startsix = Carbon::now()->subMonths(6)->startOfMonth()->timestamp;
        $endsix = Carbon::now()->subMonths(6)->endOfMonth()->timestamp;
        $startseven = Carbon::now()->subMonths(7)->startOfMonth()->timestamp;
        $endseven = Carbon::now()->subMonths(7)->endOfMonth()->timestamp;
        $starteight = Carbon::now()->subMonths(8)->startOfMonth()->timestamp;
        $endeight = Carbon::now()->subMonths(8)->endOfMonth()->timestamp;
        $startnine = Carbon::now()->subMonths(9)->startOfMonth()->timestamp;
        $endnine = Carbon::now()->subMonths(9)->endOfMonth()->timestamp;
        $startten = Carbon::now()->subMonths(10)->startOfMonth()->timestamp;
        $endten = Carbon::now()->subMonths(10)->endOfMonth()->timestamp;
        $starteleven = Carbon::now()->subMonths(11)->startOfMonth()->timestamp;
        $endeleven = Carbon::now()->subMonths(11)->endOfMonth()->timestamp;
        $this_months_values = (new $propdash->custommenuitems->monthly_real_time_feed)::whereBetween('time',[$startthis, $endthis])->sum('data');
        $one_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::whereBetween('time',[$startone, $endone])->sum('data');
        $two_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::whereBetween('time',[$starttwo, $endtwo])->sum('data');
        $three_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::whereBetween('time',[$startthree, $endthree])->sum('data');
        $four_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::whereBetween('time',[$startfour, $endfour])->sum('data');
        $five_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::whereBetween('time',[$startfive, $endfive])->sum('data');
        $six_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::whereBetween('time',[$startsix, $endsix])->sum('data');
        $seven_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::whereBetween('time',[$startseven, $endseven])->sum('data');
        $eight_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::whereBetween('time',[$starteight, $endeight])->sum('data');
        $nine_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::whereBetween('time',[$startnine, $endnine])->sum('data');
        $ten_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::whereBetween('time',[$startten, $endten])->sum('data');
        $eleven_month_agos_values = (new $propdash->custommenuitems->monthly_real_time_feed)::whereBetween('time',[$starteleven, $endeleven])->sum('data');

Please or to participate in this conversation.