The new cache() global helper in Laravel 5.3

(This is part of a series of posts on New Features in Laravel 5.3.)

  1. Introducing Laravel Echo: An In-Depth Walk-Through
  2. The new $loop variable in Laravel 5.3
  3. Customizing additional parameters in FirstOrCreate in Laravel 5.3
  4. The new cache() global helper in Laravel 5.3
  5. New JSON-column where() and update() syntax in Laravel 5.3
  6. Advanced operations with Collection::where in Laravel 5.3
  7. Image dimension validation rules in Laravel 5.3
  8. Customizing pagination templates in Laravel 5.3
  9. 5.3 feature announcement notes from Laracon
  10. Routing changes in Laravel 5.3
  11. Introducing Laravel Scout
  12. Introducing Laravel Passport
  13. Introducing Mailables in Laravel 5.3
  14. Directory structure changes in Laravel 5.3
  15. The new Notification system in Laravel 5.3
  16. Update to queue workers in Laravel 5.3
  17. Using Vue in Laravel 5.3, with the Vue bootstrap and sample component
  18. Defining console commands via closure in Laravel 5.3

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

Matt Stauffer headshot

Hi, I'm Matt Stauffer.

I'm partner & technical director at Tighten Co.

You can find me on Twitter at @stauffermatt


Like what you're reading?

I wrote an entire 450+ page book for O'Reilly: Laravel: Up and Running.

You can order the eBook or print book today.