Get "PHP 8 in a Nutshell" (Soon PHP 8.5)
Amit Merchant
Amit Merchant

A blog on PHP, JavaScript, and more

Using the new session cache in Laravel

Laravel’s cache system is a powerful tool that allows developers to store and retrieve data quickly, improving the performance of their applications. Usually, caching is done using various drivers like Redis, Memcached, Database or even the file system.

This is great when you want to cache data which are globally accessible across different users or something that is not user-specific. But what if you want to cache data that is specific to a user session? For instance, you might want to cache the user’s preferences, shopping cart items, or any other data that is relevant only to the current session.

This is where the new session cache feature in Laravel comes in handy. Introduced in a recent Laravel 12.x release, Session Cache is a feature in Laravel that allows you to cache data specifically for an individual user’s session. Unlike the global application cache, which is shared across all users, session cache data is tied to a single user’s session and is automatically cleaned up when the session expires or is destroyed.

This is useful for storing temporary data that you want to persist across multiple requests within the same session, but don’t need to keep permanently. Examples include form data, temporary calculations, API responses, or any other ephemeral data that should be tied to a specific user’s session.

How To Use Session Cache

You access the session cache using the cache() method on the session object. The session cache supports all the familiar Laravel cache methods like get, put, remember, and forget, but scoped to the current session.

Suppose you want to store a discount value for a user during their session, you can do it like this.

// Store a discount value in the session cache for 5 minutes
$request->session()->cache()->put(
    'discount', 10, now()->addMinutes(5)
);

// Retrieve the discount value from the session cache
$discount = $request->session()->cache()->get('discount');
  • The put method stores the value 10 under the key 'discount' and sets it to expire in 5 minutes.
  • The get method retrieves the value of 'discount' for the current user’s session.

Here’s one more example where you can use the session cache to store cart items for a user.

// Store the shopping cart in the session cache for 30 minutes
$request->session()->cache()->put(
    'cart', ['item1' => 2, 'item2' => 1], now()->addMinutes(30)
);

And then retrieve it like this.

// Retrieve the shopping cart from the session cache
$cart = $request->session()->cache()->get('cart');

Removing the cart after checkout.

// Remove the cart from the session cache after checkout
$request->session()->cache()->forget('cart');

Using Other Cache Methods

You can use other cache methods as well, such as remember to cache a value only if it doesn’t exist.

 // Cache a value if it doesn't exist, otherwise retrieve it
$discount = $request->session()->cache()->remember(
    'discount', 
    now()->addMinutes(5), 
    function () {
        return 10;
    }
);

If 'discount' is not already cached, the closure is executed and its result (10) is stored for 5 minutes.

Forgetting Data

To remove a cached value from the session cache.

// Remove the 'discount' value from the session cache
$request->session()->cache()->forget('discount');

Why Use Session Cache?

Here are some reasons why you might want to use session cache in your Laravel applications.

  • Isolation: Data is scoped to the user’s session, so it won’t interfere with other users.
  • Automatic Cleanup: Data is deleted when the session expires or is destroyed.
  • Convenience: Use familiar cache methods, but with session-level isolation.

In Closing

All in all, I think the session cache is a great addition to Laravel’s caching capabilities. It provides a simple and effective way to manage user-specific temporary data without the overhead of managing separate cache keys or worrying about data collisions between users.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! This is Amit, again. I write articles about all things web development. If you enjoy my work (the articles, the open-source projects, my general demeanour... anything really), consider leaving a tip & supporting the site. Your support is incredibly appreciated!

Comments?