Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A little Laravel helper function for hijacking Carbon's "now()" inside a callback
<?php
// Helper usage:
// timeTravel(Carbon::parse('one year ago'), function () {...});
function timeTravel($target, $callback) {
Illuminate\Support\Carbon::setTestNow($target);
return tap($callback(), function () {
Illuminate\Support\Carbon::setTestNow();
});
}
// Macro usage:
// Carbon::parse('last year')->timeTravel(function() {...}};
Illuminate\Support\Carbon::macro('timeTravel', function ($callback) {
$target = $this;
Illuminate\Support\Carbon::setTestNow($target);
return tap($callback(), function () {
Illuminate\Support\Carbon::setTestNow();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.