Laravel Tutorials

Working with Flash Session Data in Laravel

Published
Working with Flash Session Data in Laravel image

Laravel offers an intuitive system for managing temporary session data through its flash methods. This approach is ideal for implementing status messages, alerts, and other ephemeral notifications in your application.

The basic implementation stores data for just the next request:

$request->session()->flash('status', 'Task was successful!');

Laravel provides several specialized flash methods for different scenarios:

// Extend all flash data for another request
$request->session()->reflash();
 
// Selectively extend specific flash items
$request->session()->keep(['username', 'email']);
 
// Flash data available only in the current request
$request->session()->now('status', 'Operation completed');

Here's how these methods work in a practical notification system:

class NotificationController extends Controller
{
public function processForm(Request $request)
{
try {
DB::transaction(function () use ($request) {
// Process form data
$result = $this->processData($request->all());
 
// Flash success for next request
$request->session()->flash('message', 'Form processed successfully');
$request->session()->flash('details', [
'id' => $result->id,
'timestamp' => now()->toDateTimeString()
]);
 
// Conditional keep based on user preference
if ($request->has('show_details')) {
$request->session()->keep(['details']);
}
});
 
return redirect()->route('dashboard');
 
} catch (Exception $e) {
logger()->error('Form processing failed', ['error' => $e->getMessage()]);
 
// Immediate error for current request
$request->session()->now('error', 'Processing failed');
 
return back()->withInput();
}
}
}

Flash session data creates a streamlined approach to request-based messaging without the complexity of persistent storage mechanisms, making your application more responsive and user-friendly.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

masteringlaravel logo
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review

The latest

View all →
Cancel In-Flight Form Submissions in Inertia.js v3.7 image

Cancel In-Flight Form Submissions in Inertia.js v3.7

Read article
Laravel Starter Kits Now Ship with Vite+ image

Laravel Starter Kits Now Ship with Vite+

Read article
Pessimistic Locking in Laravel Eloquent with refreshForUpdate() image

Pessimistic Locking in Laravel Eloquent with refreshForUpdate()

Read article
Mask Query Bindings in Laravel Exception Messages image

Mask Query Bindings in Laravel Exception Messages

Read article
whereBinary(): Case-Sensitive MySQL Queries in Laravel image

whereBinary(): Case-Sensitive MySQL Queries in Laravel

Read article
Compile PHP to Native Binaries with TypePHP image

Compile PHP to Native Binaries with TypePHP

Read article