When building Single Page Applications with Laravel and Inertia.js, handling session alerts (like "Workspace updated" or "Member removed") can be tricky because traditional Laravel session flashes don't automatically trigger state re-renders in React.
Here is how to set up clean, real-time flash notifications using Laravel 11, Inertia.js, and React components.
1. Share Flash Data via Middleware
Inertia provides the HandleInertiaRequests middleware to bridge Laravel sessions into React props. Update app/Http/Middleware/HandleInertiaRequests.php:
public function share(Request $request): array
{
return array_merge(parent::share($request), [
'flash' => [
'success' => fn () => $request->session()->get('success'),
'error' => fn () => $request->session()->get('error'),
],
]);
}
Using closure wrappers (fn () => ...) ensures session messages are lazily evaluated only when needed during responses.
2. Flashing Messages in Controllers
Now you can send flash feedback from any Laravel controller:
// Success alert
return back()->with('success', 'Workspace settings updated successfully.');
// Error alert
return back()->with('error', 'You do not have permission to perform this action.');
3. Rendering Banners in React Components
Create a reusable FlashBanner.jsx component to render incoming alerts:
import { usePage } from '@inertiajs/react';
import { useState, useEffect } from 'react';
export default function FlashBanner() {
const { flash } = usePage().props;
const [visible, setVisible] = useState(false);
useEffect(() => {
if (flash.success || flash.error) {
setVisible(true);
}
}, [flash]);
if (!visible || (!flash.success && !flash.error)) return null;
return (
<div className={`p-4 mb-4 text-sm rounded-lg flex justify-between items-center ${
flash.success ? 'bg-green-100 text-green-800 dark:bg-green-900/50 dark:text-green-300' :
'bg-red-100 text-red-800 dark:bg-red-900/50 dark:text-red-300'
}`}>
<span>{flash.success || flash.error}</span>
<button onClick={() => setVisible(false)} className="font-bold ml-4">✕</button>
</div>
);
}
Place <FlashBanner /> inside your main layout wrapper (AuthenticatedLayout.jsx) to display feedback automatically across every page of your app!
Wrap Up
By exposing Laravel session keys through Inertia's share() method, your React components can react instantly to backend actions without writing extra API event handlers.
⚡ Save time on your next SaaS project:
Check out the Pro Laravel 11 + React SaaS Starter Kit on Gumroad featuring workspace management, dark mode, Stripe billing, and flash messaging pre-configured out of the box. Free open-source tier available on GitHub.
Top comments (0)