Sometimes you need to access certain data on numerous pages within your application. For example, a common use-case for this is showing the current user in the site header. Passing this data manually in each response isn't practical. In these situations shared data can be useful.
The server-side adapters provide a way to preassign shared data for each request. This is typically done outside of your controllers. Shared data will be automatically merged with the page props provided in your controller.
/*
|----------------------------------------------------------------
| Via the HandleInertiaRequests middleware (recommended)
|----------------------------------------------------------------
*/
class HandleInertiaRequests extends Middleware
{
public function share(Request $request)
{
return array_merge(parent::share($request), [
// Synchronously
'appName' => config('app.name'),
// Lazily
'auth.user' => fn () => $request->user()
? $request->user()->only('id', 'name', 'email')
: null,
]);
}
}
/*
|----------------------------------------------------------------
| Manually
|----------------------------------------------------------------
*/
use Inertia\Inertia;
// Synchronously
Inertia::share('appName', config('app.name'));
// Lazily
Inertia::share('user', fn (Request $request) => $request->user()
? $request->user()->only('id', 'name', 'email')
: null
);
Once you've shared the data server-side, you'll then be able to access it within your page components as props. Shared data can even be accessed in non-page components, although not as props in those cases. Here's an example of how to do this in a layout component.
<template>
<main>
<header>
You are logged in as: {{ user.name }}
</header>
<content>
<slot />
</content>
</main>
</template>
<script>
import { computed } from 'vue'
import { usePage } from '@inertiajs/inertia-vue3'
export default {
setup() {
const user = computed(() => usePage().props.value.auth.user)
return { user }
},
}
</script>
Another great use-case for shared data is flash messages. These are messages stored in the session only for the next request. You'll often set a flash message after completing a task and before redirecting to a different page.
Here's a simple way to implement flash messages in your Inertia applications. First, share the flash message on each request.
class HandleInertiaRequests extends Middleware
{
public function share(Request $request)
{
return array_merge(parent::share($request), [
'flash' => [
'message' => fn () => $request->session()->get('message')
],
]);
}
}
Next, display the flash message in a front-end component, such as the site layout.
<template>
<main>
<header></header>
<content>
<div v-if="$page.props.flash.message" class="alert">
{{ $page.props.flash.message }}
</div>
<slot />
</content>
<footer></footer>
</main>
</template>