Larave Extracting Two Dates Out of One

avatar
Apr 04, 2023 · Snippet · 1 min, 79 words

Extracting two dates out of one, like in the case of startOfMonth & endOfMonth, make sure not to apply both functions on the same date variable. Otherwise, you get unexpected results. 👇

class GetUserTokesConsuemed
{
  public function execute(User $user, Carbon $date = null):mixed
  {
    $date = $date ?? Carbon::now();
    
    // ❌ don't do
    $startDate = $date->startOfMonth();
    $endDate = $date->endOfMonth();
    
    // ✔️ do
    $startDate = $date->startOfMonth();
    $endDate = $date->copy()->endOfMonth(); // make a copy
    
    // ...
  }
}

Comments

No comments yet…