In Laravel Inertia you can define shared data in which all components will share the value. The location of where you can define this is the "HandleInertiaRequests" middleware class.
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Inertia\Middleware;
use Tightenco\Ziggy\Ziggy;
class HandleInertiaRequests extends Middleware
{
/**
* The root template that is loaded on the first page visit.
*
* @var string
*/
protected $rootView = 'app';
/**
* Determine the current asset version.
*
* @param \Illuminate\Http\Request $request
* @return string|null
*/
public function version(Request $request)
{
return parent::version($request);
}
/**
* Define the props that are shared by default.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function share(Request $request)
{
return array_merge(parent::share($request), [
'auth' => [
'user' => $request->user(),
],
'ziggy' => function () {
return (new Ziggy)->toArray();
},
]);
}
}
From this file you can put all of your shared data in the share() method as shown above. To access the data on your other components you can call the $page variable and then access it via the "props" key and the data key that you have defined. For example to get a user you can access it like below.
<span v-text="$page.props.auth.user"/>
Leave a reply