#[Session]
Persist property values in the Laravel session across page loads.
Basic Usage
Mark a property with #[Session] to automatically save and restore its value from the Laravel session.
use LiVue\Attributes\Session;
class SearchPage extends Component
{
#[Session]
public string $search = '';
#[Session]
public string $sortBy = 'name';
#[Session]
public array $filters = [];
}
Now when users refresh the page or navigate away and back, their search term, sort preference, and filters are preserved.
Custom Session Key
By default, the session key is livue.{ComponentName}.{property}. You can customize it:
class ProductList extends Component
{
// Custom static key
#[Session(key: 'product_filters')]
public array $filters = [];
// Namespaced key
#[Session(key: 'app.products.view_mode')]
public string $viewMode = 'grid';
}
Dynamic Session Keys
Use {property} placeholders to create dynamic keys based on other property values:
class UserDashboard extends Component
{
public int $userId;
// Each user gets their own session key
#[Session(key: 'dashboard_prefs_{userId}')]
public array $preferences = [];
// Multiple placeholders
#[Session(key: 'cart_{userId}_{storeId}')]
public array $cartItems = [];
public int $storeId = 1;
}
Practical Example
A filter panel that remembers user preferences:
class OrderList extends Component
{
#[Session]
public string $status = 'all';
#[Session]
public int $perPage = 10;
public function getOrders()
{
return Order::query()
->when($this->status !== 'all',
fn($q) => $q->where('status', $this->status))
->paginate($this->perPage);
}
}
<div>
<select v-model="status">
<option value="all">All</option>
<option value="pending">Pending</option>
<option value="completed">Completed</option>
</select>
<select v-model="perPage">
<option value="10">10 per page</option>
<option value="25">25 per page</option>
<option value="50">50 per page</option>
</select>
<p class="text-sm">
Refresh the page - your filters persist!
</p>
</div>
#[Session] vs #[Url]
Both persist state, but they work differently:
| Attribute | Storage | Shareable | Best For |
|---|---|---|---|
#[Session] |
Server session | No | User preferences, private state |
#[Url] |
URL query string | Yes | Filters, search, bookmarkable state |
You can combine both for different properties based on whether the state should be shareable.
How It Works
-
1
On mount
Values are read from Laravel session using
session()->get()and set on properties. -
2
On dehydrate
Current values are saved to session using
session()->put()after each request. -
3
Session lifetime
Values persist according to your Laravel session configuration (typically until browser close or timeout).