Session Flash Data in Laravel: Managing Temporary Messages

Session Flash Data in Laravel: Managing Temporary Messages

Learn how to effectively manage temporary session data in Laravel using flash methods, perfect for status messages, alerts, and temporary user notifications.

Basic Flash Data

Store data for the next request:

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

Extended Flash Data Methods

// Keep all flash data
$request->session()->reflash();

// Keep specific items
$request->session()->keep(['username', 'email']);

// Flash for current request only
$request->session()->now('status', 'Task was successful!');

Real-World Example

Here's a practical implementation for an order processing system:

class OrderController extends Controller
{
    public function store(OrderRequest $request)
    {
        try {
            $order = Order::create($request->validated());
            
            // Flash success message for next request
            $request->session()->flash('status', 'Order created successfully!');
            
            return redirect()->route('orders.show', $order);
            
        } catch (Exception $e) {
            // Flash error for current request only
            $request->session()->now('error', 'Failed to create order.');
            return back()->withInput();
        }
    }

    public function update(OrderRequest $request, Order $order)
    {
        $order->update($request->validated());

        // Flash multiple messages
        $request->session()->flash('status', 'Order updated!');
        $request->session()->flash('order_id', $order->id);
        
        // Keep these flashed items for extra request
        if ($request->has('preview')) {
            $request->session()->keep(['status', 'order_id']);
        }

        return redirect()->route('orders.index');
    }

    public function processMultiStep(Request $request)
    {
        // Keep form data between steps
        $request->session()->reflash();
        
        return redirect()->route('orders.step-' . $request->next_step);
    }
}

// In your blade view
@if (session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
        @if (session('order_id'))
            <small>Order ID: {{ session('order_id') }}</small>
        @endif
    </div>
@endif

Flash session data provides an elegant way to pass temporary messages between requests in your Laravel application.

If this guide was helpful to you, subscribe to my daily newsletter and give me a follow on X/Twitter and Bluesky. It helps a lot!

Subscribe to Harris Raftopoulos

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe