The new cache() global helper in Laravel 5.3

Posted on July 06, 2016 | By Matt Stauffer


Warning: This post is over a year old. I don't always update old posts with new information, so some of this information may be out of date.

Time for another new feature in Laravel 5.3!

Shortcut global helpers in Laravel

As I was writing my book I noticed a pattern in the global helper functions like session() and, in some ways, cookie(). There are three primary functions that they can perform: get a value, put a value, or return an instance of their backing service.

For example:

  • session('abc', null) gets the value of abc, or an optional fallback of null.
  • session(['abc' => 'def']) sets the value of abc to def.
  • session() returns an instance of the SessionManager.

The third option means you can use session()->all() (or any other methods) just like you would Session::all().

I mentioned that it seems like there should be a cache() helper, and before I could even think much more about it, Jeffrey (Way) had already written one up. So! Behold! The global cache() helper, new in Laravel 5.3.

The cache() global helper

Like session(), the cache() global helper can perform three primary functions: get, put, or return an instance of the backing service.

For example:

  • cache('abc', null) gets the cached value of abc, or an optional fallback of null.
  • cache(['abc' => 'def'], 5) sets the value of abc to def, for the duration of 5 minutes.
  • cache() returns an instance of the CacheManager.

The third option means you can use cache()->forever() (or any other methods) just like you would Cache::forever().

That's it! Enjoy!


Comments? I'm @stauffermatt on Twitter


Tags: laravel  •  laravel 5.3