Sure! Here’s a detailed and original blog post (~1500 words) on the topic “How to Share Data in Laravel with Vue.js and Inertia.js”, written in clear and professional English:
How to Share Data in Laravel with Vue.js and Inertia.js
Modern web development often requires combining the strengths of both server-side and client-side frameworks. Laravel, Vue.js, and Inertia.js form a powerful stack that allows you to build full-featured, modern web applications with the comfort of server-side routing and client-side interactivity.
In this post, we’ll focus on a key aspect of building apps using this stack: sharing data between Laravel (backend) and Vue.js (frontend) using Inertia.js. This is essential for things like authenticated user info, flash messages, app settings, and more.
What is Inertia.js?
Before diving into shared data, let’s understand where Inertia.js fits in.
Inertia.js is a JavaScript library that allows you to build single-page applications (SPAs) using classic server-side frameworks like Laravel. It replaces the need for an API and a frontend router like Vue Router or React Router.
With Inertia, you send data from your controllers to your frontend components (e.g., Vue) just like you would in a traditional Laravel view. This means no JSON APIs, no Axios for page loads—Inertia handles it all.
Why Share Data Globally?
There are many use-cases where you need to access common data across your application:
- The currently authenticated user
- Flash messages (success or error)
- Application settings (e.g., app name, locale)
- CSRF tokens
- Notifications or unread messages
- Permissions or roles
Rather than sending this data from every controller manually, Inertia allows you to share global data that is automatically available on every page component.
How Inertia Shares Data
Inertia provides a share method that you can use within a Laravel middleware or a service provider. The data shared here becomes available in all Vue components rendered by Inertia.
The basic setup looks like this:
Inertia::share('key', 'value');
You can share dynamic values (like the logged-in user) by passing a closure:
Inertia::share('auth.user', function () {
return Auth::user();
});
This makes auth.user available in all your frontend Vue components.
Step-by-Step: Sharing Data Using Inertia.js
Let’s walk through a full implementation.
1. Laravel + Inertia + Vue Setup
If you’re starting from scratch, install Laravel and add the required packages:
laravel new laravel-inertia-app
cd laravel-inertia-app
composer require inertiajs/inertia-laravel
npm install @inertiajs/inertia @inertiajs/inertia-vue3 vue@3
Install the Inertia Vue 3 adapter:
npm install @inertiajs/vue3
Now update resources/js/app.js:
import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/vue3'
createInertiaApp({
resolve: name => require(`./Pages/${name}.vue`),
setup({ el, App, props, plugin }) {
createApp({ render: () => h(App, props) })
.use(plugin)
.mount(el)
},
})
2. Create a Shared Data Middleware
To globally share data in Laravel via Inertia, create a middleware:
php artisan make:middleware HandleInertiaRequests
Edit the newly created middleware at app/Http/Middleware/HandleInertiaRequests.php:
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Inertia\Middleware;
use Illuminate\Support\Facades\Auth;
class HandleInertiaRequests extends Middleware
{
public function share(Request $request): array
{
return array_merge(parent::share($request), [
// Share authenticated user
'auth' => [
'user' => fn () => $request->user(),
],
// Share flash messages
'flash' => [
'success' => fn () => $request->session()->get('success'),
'error' => fn () => $request->session()->get('error'),
],
// Share app config
'appName' => config('app.name'),
]);
}
}
Register this middleware in App\Http\Kernel.php by replacing the default:
protected $middlewareGroups = [
'web' => [
// Other middlewares...
\App\Http\Middleware\HandleInertiaRequests::class,
],
];
Now all pages rendered via Inertia will have access to auth, flash, and appName.
3. Using Shared Data in Vue Components
Let’s say you want to show the authenticated user’s name in the navigation bar.
In your Vue component (e.g., resources/js/Layouts/AppLayout.vue):
<script setup>
import { usePage } from '@inertiajs/vue3'
const page = usePage()
const user = page.props.auth.user
</script>
<template>
<nav class="bg-white shadow">
<div class="container">
<span v-if="user">Hello, {{ user.name }}</span>
</div>
</nav>
</template>
Similarly, to show flash messages:
<script setup>
const flash = usePage().props.flash
</script>
<template>
<div v-if="flash.success" class="alert alert-success">
{{ flash.success }}
</div>
<div v-if="flash.error" class="alert alert-danger">
{{ flash.error }}
</div>
</template>
4. Setting Flash Messages in Controller
To trigger flash messages, simply use Laravel’s session flash method:
return redirect()->route('dashboard')
->with('success', 'Welcome back!');
The flash message will now be available globally in Vue via page.props.flash.success.
5. Share Dynamic Data
You can also share dynamic data like notification counts:
'notifications' => fn () => Auth::user()?->unreadNotifications()->count() ?? 0,
And access them in Vue:
<span class="badge">{{ $page.props.notifications }}</span>
6. Share Settings or Constants
If you have settings you want available everywhere (like site name, supported languages), define them in config/app.php or a custom config, then share them:
'settings' => [
'siteName' => config('app.name'),
'supportedLanguages' => ['en', 'fr', 'de'],
]
And use in Vue:
<h1>{{ $page.props.settings.siteName }}</h1>
Tips for Using Shared Data Efficiently
- Use closures to avoid unnecessary database queries on every request.
- Avoid large datasets in shared props to reduce payload size.
-
Use nested keys (like
auth.user) for better structure and readability. -
Group related data logically (e.g., all auth data in
auth, all settings insettings).
Troubleshooting Common Issues
-
Props not updating? Ensure your middleware is correctly registered and not cached. Run
php artisan route:clearandphp artisan optimize:clear. -
Vue errors accessing props? Make sure you’re using
usePage()properly and destructuring the correct keys. -
Flash messages not appearing? Double-check your controller is using
with()and that you’re accessing the right property in Vue.
Conclusion
Sharing data between Laravel and Vue using Inertia.js provides a smooth and efficient way to build dynamic, modern web apps. Whether it’s user information, flash messages, or app settings, Laravel’s integration with Inertia makes global data sharing incredibly straightforward.
By leveraging middleware to define shared props, and usePage() in Vue to access them, you can maintain a clean separation of logic and presentation while still enjoying the convenience of a full SPA-like experience.
Key Takeaways:
- Use
Inertia::share()in a middleware to define global props. - Access shared data in Vue using
usePage(). - Share user data, flash messages, config values, and more.
- Keep shared data small and use closures to optimize performance.


Leave a Reply