Back to Course |
Vue Inertia + 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 $page.props and then keys from the array. So, to access the message, the full path would be $page.props.flash.message.

resources/js/Layouts/App.vue:

<script setup>
import { Link } from '@inertiajs/vue3'
</script>
 
<template>
<div class="min-h-screen bg-gray-100">
// ...
 
<main>
<div class="py-12">
<div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
<div class="overflow-hidden bg-white shadow-sm sm:rounded-lg">
<div class="border-b border-gray-200 bg-white p-6">
<div v-if="$page.props.flash.message" class="mb-4 rounded-md bg-blue-100 px-3 py-2 text-blue-700">
{{ $page.props.flash.message }}
</div>
 
<slot/>
</div>
</div>
</div>
</div>
</main>
</div>
</template>

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 Vue components as a $page.props object.