Back to Course |
React.js + Inertia in Laravel 11: From Scratch

Flash Success Messages in Inertia

Let's show some success messages when submitting the form.

It is very common to show some success message when redirecting back.

app/Http/Controllers/PostController.php:

class PostController extends Controller
{
// ...
 
public function store(StorePostRequest $request): RedirectResponse
{
Post::create($request->validated());
 
return redirect()->route('posts.index')
->with('message', 'Post created successfully.');
}
}

But how do we catch this message in Inertia? We must pass that variable as a shared data using Middleware.

app/Http/Middleware/HandleInertiaRequests.php:

class HandleInertiaRequests extends Middleware
{
protected $rootView = 'layouts.app';
 
public function version(Request $request): ?string
{
return parent::version($request);
}
 
public function share(Request $request): array
{
return array_merge(parent::share($request), [
'flash' => [
'message' => fn () => $request->session()->get('message')
],
]);
}
}

We can add the message in the App layout for the front-end and conditionally show it.

To access shared data, we can use usePage().props and then keys from the array. So, to access the message, the full path would be usePage().props.flash.message.

resources/js/Layouts/AppLayout.jsx:

import { Link } from '@inertiajs/react';
import { Link, usePage } from '@inertiajs/react';
 
export default function AppLayout({ children }) {
const { flash } = usePage().props;
 
return (
<div className="min-h-screen bg-gray-100 dark:bg-gray-900">
// ...
 
<main>
<div className="py-12">
<div className="mx-auto max-w-7xl sm:px-6 lg:px-8">
<div className="overflow-hidden bg-white shadow-sm sm:rounded-lg">
<div className="border-b border-gray-200 bg-white p-6">
{flash.message && (
<div className="mb-4 rounded-md bg-blue-100 px-3 py-2 text-blue-700">{flash.message}</div>
)}
 
{children}
</div>
</div>
</div>
</div>
</main>
</div>
);
}

After creating a new post, we will see the notification message.


Shared data is used for global variables, and later in this course, we will use it for other things like authentication or permissions.

But generally, whatever you put in the share() will be available in the React components as a prop within usePage().