Search

Laravel 5: Accessing the Cache System With cache

April 14, 2018 —John Koster

The cache helper function can be used as a convenient way to access the Laravel cache store, retrieve existing items from the cache, and to place new items in the cache.

The behavior of the cache helper function is determined by the number and types of arguments supplied.

#Signature

The signature of the cache function is:

1function cache();
2 
3function cache(
4 string $name
5);
6 
7function cache(
8 string $name,
9 $defaultValue
10);
11 
12function cache(
13 [
14 $name,
15 $value
16 ],
17 $expirationInMinutes
18);

#Example Use

The following examples demonstrate returning the cache store instance and then checking if a cache item exists with a specific key:

1// Gaining access to the cache store and checking if
2// an item already exists in the cache.
3if (cache()->has('key')) {
4 // The cache contains the provided key.
5}

In the next example, we will attempt to retrieve an item from the cache; if the item does not exist within the cache, we have specified a default value that will be returned instead (there is one example that returns a literal string as its default value, and another that executes a callback function to determine the default value; both examples return the same result):

1$cacheValue = cache('message', 'Hello, Universe');
2 
3$cacheValueTwo = cache('message', function () {
4 return 'Hello, Universe';
5});

After the above code has executed, both the $cacheValue and $cacheValueTwo variables will contain the value Hello, Universe.

The following example will set a new cache value that will expire in five minutes:

1// Put a new item in the cache for five minutes.
2cache([
3 'message' => 'Hello, World'
4], 5);
5 
6$cacheValue = cache('message', 'Hello, Universe');

Now, when the above code has executed, the value Hello, World would have been placed in the cache and the value of $cacheValue would also be Hello, World.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.