Home / Snippets / How to Access Shared Data on Laravel Inertia
How to Access Shared Data on Laravel Inertia cover

How to Access Shared Data on Laravel Inertia

2K

2 years ago

0 comments

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"/>
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this