Display Flash Messages Using Laravel and Inertia

Paulund - May 26 - - Dev Community

In Laravel it's common practise to after a form submit to redirect the user back to the form page and display a flash
message. In this tutorial we will see how to display flash messages using Laravel and Inertia.

With Laravel you will do this with some helper route methods, in your controller you will have something like this:

return redirect()->back()->with('success', 'Form submitted successfully');
Enter fullscreen mode Exit fullscreen mode

This will add a success key to the session with the value Form submitted successfully. If you're using blade file you can
then display this message like this:

@if (session('success'))
    <div class="alert alert-success">
        {{ session('success') }}
    </div>
@endif
Enter fullscreen mode Exit fullscreen mode

But this won't work with Inertia, because Inertia is a client-side framework and it doesn't have access to the session. So
we need to pass the flash messages to the client side.

To do this we will take advantage of the Inertia middleware HandleInertiaRequests this middleware is responsible for
passing the data to the client side. We will add a new key to the share method in the HandleInertiaRequests middleware
called flash and we will pass the session flash messages to the client side.

// app/Http/Middleware/HandleInertiaRequests.php

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

These will come through to your Vue components as page props page.props.flash?.success and page.props.flash?.error.

Now in your Vue component you can access the flash messages like this:

<template>
    <div>
        <div v-if="$page.props.flash.success" class="alert alert-success">
            {{ $page.props.flash.success }}
        </div>
        <div v-if="$page.props.flash.error" class="alert alert-danger">
            {{ $page.props.flash.error }}
        </div>
    </div>
</template>
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .