Session (#[Session])

In Livewire 3, working with sessions has become even more convenient thanks to the #[Session] attribute. This allows you to bind a component property directly to a session value: Livewire will automatically write changes to the session and read them during initialization.

Here is a detailed breakdown of how it works and its nuances.


1. Using the #[Session] Attribute

The easiest way to persist state between page navigations or refreshes is to add the attribute to a public property.

PHP
use Livewire\Component;
use Livewire\Attributes\Session;

class Counter extends Component
{
    #[Session] 
    public $count = 0;

    public function increment()
    {
        // The value in the session will be updated automatically on every call
        $this->count++;
    }
}

How it works “under the hood”:

  • Initial Render: Livewire looks for a key in the session (by default, it uses the property name, e.g., count).

  • Retrieval: If the key is found, the $count property will take the value from the session.

  • Defaulting: If not found, the default value (0) will be used.

  • Synchronization: Any change to the property within the code will cause Livewire to update the data in the Laravel session.


2. Using a Custom Key

If you want multiple components to share the same session variable, or if you simply want to define a specific key name, pass it into the attribute:

PHP
#[Session(key: 'user_theme_preference')]
public $theme = 'light';

3. Standard Laravel Approach (Session Helper)

The #[Session] attribute is great for property synchronization, but for classic tasks (like Flash messages confirming an operation’s success), it is better to use standard Laravel methods inside component methods.

PHP
public function save()
{
    // Saving logic...

    session()->flash('status', 'Data successfully saved!');
    
    return $this->redirect('/dashboard');
}

And in the Blade template:

HTML
@if (session()->has('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
@endif