Getting started with Livewire session properties

Getting started with Livewire session properties

Livewire's Session Properties is a simple yet powerful feature for enhancing user experience and maintaining state across page refreshes.

If you've been tinkering with Laravel Livewire, you know it's all about making life easier. Today, let's dive into one of those neat features that just shipped in the new v3.4.0 release: Session Properties.

What are Session Properties?

If you want to maintaining state across page refreshes in your Livewire components, this is for you. Session Properties offer a seamless way to persist property values across page refreshes or changes. This is achieved using the #[Session] attribute. When you add this attribute to a property in your component, Livewire automatically stores its value in the session whenever it changes. This ensures that the property's value is retained even after a page refresh.

Basic Usage

Imagine you have a ShowProducts component allowing users to filter posts by a search term. Here's how you'd typically set it up:

1use Livewire\Attributes\Computed;
2use Livewire\Attributes\Session;
3use Livewire\Component;
4use App\Models\Post;
5 
6class ShowProducts extends Component
7{
8 #[Session]
9 public $search;
10 
11 #[Computed]
12 protected function products()
13 {
14 return Product::query()
15 ->when($this->search, fn($query) => $query->where('name', 'like', '%'.$this->search.'%')
16 ->get();
17 }
18 
19 public function render()
20 {
21 return view('livewire.show-products';
22 }
23}

In this example, the #[Session] attribute added to the $search property ensures that the search term is saved in the user's session. Users can refresh the page without losing their search value - a small but significant quality-of-life improvement.

Custom Session Keys

By default, Livewire uses a dynamically generated key for storing property values in the session, combining the component name and property name. This ensures uniqueness across different components and instances.

However, if you need more control over the session key used, you can specify it using the key: parameter:

1use Livewire\Attributes\Computed;
2use Livewire\Attributes\Session;
3use Livewire\Component;
4use App\Models\Post;
5 
6class ShowProducts extends Component
7{
8 #[Session(key: 'my-custom-key')]
9 public $search;
10 
11 // ...
12}

With this setup, Livewire will use the specified key ('my-custom-key' in this case) when storing and retrieving the $search property's value.

To navigate
Press Enter to select