1

In Laravel 5.3, I've written a collection designed to cycle through a user's bills and determine whether they were paid within a given time frame.

return $dates->map(function ($item, $key) use ($interval) {
    $bills = DB::table('bills')
    ->where('provider_id', Auth::user()->company()->first()->id)
    ->whereBetween(
        'date_paid', [$item, $this->returnRangeFromInterval($item, $interval)]
    )
    ->where('status', 'paid')
    ->get();
    return $bills->pluck('amount_due')->sum();
});

That date_paid attribute is stored as UTC, but to return an accurate sum, I need to shift that date to a user's timezone—which I have stored on the User object. How could I accomplish this in the collection above?

It looks as though I can use a MYSQL method called convert_tz if absolutely necessary, but I'm interested first and foremost in the "Laravel Way".

Cameron Scott
  • 1,276
  • 2
  • 17
  • 37
  • Here is the example using Carbon[http://carbon.nesbot.com/docs/] that converts the `Europe/Stockholm` to `UTC`. You could use it to change your timezone from `UTC` to any other. You might need to perform some tweaks http://stackoverflow.com/a/21608708/3887342 – PaladiN Jan 27 '17 at 04:41

1 Answers1

0

Collections to the rescue. I was able to use map to modify the attribute in question, and then return a collection of bills with that modified attribute. Also reduced the number of queries I was making, too.

$bills = DB::table('bills')
    ->where('provider_id', Auth::user()->company()->first()->id)
    ->where('status', 'paid')
    ->get();

$adjustedBills = $bills->map(function ($bill, $key) {
    $bill->date_paid = Carbon::parse($bill->date_paid)->timezone('America/New_York')->toDateTimeString();
    return $bill;
});

return $dates->map(function ($item, $key) use ($interval, $adjustedBills) {
    return $adjustedBills->filter(function ($date, $key) use ($item, $interval) {
        return $date->date_paid >= $item && $date->date_paid <= $this->returnRangeFromInterval($item, $interval);
    })->pluck('amount_due')->sum();
})->flatten();
Cameron Scott
  • 1,276
  • 2
  • 17
  • 37