Sessions
Basic Usage
Sessions allow your application to store data on the server and make it available across multiple requests for the same user. SigmaPHP provides a dedicated session manager that simplifies reading, writing, and removing session values without interacting directly with native PHP session functions. This makes state management predictable and easy to use inside controllers.
The session manager is available in every controller through
$this->session(), giving you access to user-related data such as
authentication information, preferences, temporary state, and workflow data.
public function sessionExample()
{
/*
|------------------------------------------------------------
| Storing Data
|------------------------------------------------------------
*/
$this->session()->set('user_id', 15);
// Expected result:
// Session now contains user_id = 15
/*
|------------------------------------------------------------
| Reading Data
|------------------------------------------------------------
*/
$userId = $this->session()->get('user_id');
// Result: 15
/*
|------------------------------------------------------------
| Checking Existence
|------------------------------------------------------------
*/
if ($this->session()->has('user_id')) {
// true if session value exists
}
/*
|------------------------------------------------------------
| Removing Data
|------------------------------------------------------------
*/
$this->session()->delete('user_id');
// Session value removed
}
Flash Messages
Flash messages are temporary session values that exist for only one request cycle. They are commonly used to display success, warning, or error messages after a redirect. SigmaPHP provides a convenient way to store flash messages from the controller and automatically make them available inside templates.
public function store()
{
// ... save data
$this->flash('success', 'Profile updated successfully');
return $this->redirect('/profile');
}
Inside your template, flash messages can be rendered as follows:
<ul>
{% for $message in $flashMessages %}
{{ $message }}
{% end_for %}
</ul>
Repopulate Old Input
When working with forms, it is often necessary to repopulate previously submitted
values after validation fails. The saveOldValues() method stores both
GET and POST input values in the session so they can be reused after a redirect,
improving user experience by preventing data loss.
public function submit(Request $request)
{
if (!$request->has('email')) {
// store previous GET and POST values
$this->saveOldValues();
$this->flash('error', 'Email field is required');
return $this->redirect('/register');
}
return $this->response('Form submitted successfully');
}
After redirecting, previously entered values can be reused inside the template to automatically refill form inputs, allowing users to correct mistakes without retyping their data.
<input type="email" name="email" value="{{ $oldValues['email'] ?? '' }}" />