Landscape cutout

Flashing messages from Laravel in Inertia.js

Created by Jonathan Reinink, Inertia.js is "a Turbolinks inspired library that makes it super easy to create server-driven single-page apps." While developing an app with Laravel, Vue and Inertia.js I wanted to redirect the user after updating some data to a new page, and show a flash message.

As an example, a controller could include something like this:

return redirect()->route('posts.index')->withFlash('the post is saved!');

Inertia.js however renders the components differently, and does not take the incoming flash message with it:

Inertia::render('Posts/Index', $posts);

This means that the flash message seems to not be passed to the Vue page. Luckily, there is a way to send data to Inertia besides through every render() call. That way is through Inertia::share($key, $value).

For the flash messages, I created a new middleware called ShareFlashes and added it to the web middleware group in app/Http/Kernel.php to have it loaded on every request (you can use the artisan make:middleware command for this).

The middleware itself does not contain much:


namespace App\Http\Middleware;

use Closure;
use Inertia\Inertia;

class ShareFlashes
     * Handle an incoming request.
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     * @return mixed
    public function handle($request, Closure $next)
        Inertia::share('flash', session('flash', false));

        return $next($request);

In a vue component it is now possible to call for the flash message prop:

if ( != false) {
    // show flash message

Thanks to the middelware, the flash message prop will be false when there is none, or otherwise contain the (translated) message.

update In this commit Jonathan Reinink shows a much simpler way to use flash messages without a middleware but with a dedicated Vue component.