Freezing Time in Laravel Tests

In your Laravel tests, you might sometimes need to freeze the time.

This is particularly useful if you're trying to make assertions based on timestamps or need to make queries based on dates and/or times.

1// To freeze the time, you used to be able to write this at the time top of your tests:
2Carbon::setTestNow(Carbon::now());
3// You could also use the "travelTo" method:
4$this->travelTo(Carbon::now());
5// You can now use the new "freezeTime" method to keep your code readable and obvious:
6$this->freezeTime();

Tip given by @AshAllenDesign

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord