Cache TTL Change Coming to Laravel 5.8

Tutorials

January 28th, 2019

Cache TTL Change Coming to Laravel 5.8

Starting in Laravel 5.8, the time to live (TTL) used when passing an integer to cache drivers will be in ‌seconds instead of minutes. Caching in seconds gives users more granular control over cache duration, and will conform with PSR-16:

The Time To Live (TTL) of an item is the amount of time between when that item is stored, and it is considered stale. The TTL is normally defined by an integer representing time in seconds, or a DateInterval object.

From Laravel 5.0 to the current stable Laravel 5.7, when you pass an integer to cache storage operations like put() and remember(), the duration is represented in minutes:

Cache::remember('active-posts', 5, function () {
return Post::active()->get();
});

To ease your upgrade path from earlier versions (5.5 or later) to Laravel 5.8, you can also pass a DateTimeInterface or a DateInterval to Cache::put(). Using a DateTime or an interval is something you can do now, without having to find/replace and convert everything to seconds, and might bring more clarity to your cache times as a bonus:

Cache::remember('active-posts', \DateInterval::createFromDateString('5 minutes'), function () {
return Post::active()->get();
});

Here’s an example using Carbon’s addMinutes():

Cache::remember('active-posts', now()->addMinutes(5), function () {
return Post::active()->get();
});

You can see the changes made by Dries Vints for the upcoming Laravel 5.8 release!

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.