0

I’m using Inertia.js with Vue 3, and I want to show a success message when a form is submitted successfully.
In my controller I have:

public function store(Request $request)
{
    $validated = $request->validate([
        'name' => 'required|string|max:255'
    ]);

    Model::create($validated);

    return redirect()->back()->with('success', 'Record saved successfully!');
}

In my Vue component, I tried to access the message like this:

<template>
  <div v-if="flash.success" class="alert">
    {{ flash.success }}
  </div>
</template>

<script setup>
import { usePage } from '@inertiajs/vue3'
const { props } = usePage()
const flash = props.flash
</script>

But flash.success is always undefined even though I see the message if I dd(session('success')) in the controller.

I tried using usePage().props.flash.success, refreshing manually, and adding middleware for sessions, but nothing worked.
I expected the message "Record saved successfully!" to appear in my Vue alert after submitting the form.
How can I correctly access Laravel flash messages inside my Vue component when using Inertia?

1 Answer 1

0

Yes — to make Laravel flash messages available in Inertia, just share them globally in your middleware.

Edit app/Http/Middleware/HandleInertiaRequests.php and add:

public function share(Request $request): array
{
    return array_merge(parent::share($request), [
        'flash' => [
            'success' => $request->session()->get('success'),
            'error' => $request->session()->get('error'),
        ],
    ]);
}

Then in your Vue component:

<template>
  <div v-if="flash.success" class="bg-green-500 text-white p-2 rounded">
    {{ flash.success }}
  </div>
</template>

<script setup>
import { usePage } from '@inertiajs/vue3'
const flash = usePage().props.flash
</script>

And in your controller:

return redirect()->back()->with('success', 'Record saved successfully!');

That’s all — your message will show up after the redirect.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.