inertiajs / inertia-laravel

The Laravel adapter for Inertia.js.
https://inertiajs.com
MIT License
1.99k stars 222 forks source link

Add persistent properties #621

Closed lepikhinb closed 1 month ago

lepikhinb commented 2 months ago

The PR introduces an ability to persist properties on partial requests.

When making a partial reload, Inertia will only evaluate and include on the response properties, specified in the only array. This adds some extra inconvenience when you need to carry some common data between pages (e.g. current user data).

Inertia::persist('auth.user');
// or
inertia()->persist(['auth.user'])
router.visit(url, {
  only: ['billing'],
})
$props = [
    // Included on partial reload
    'auth' => [
        'user' => new LazyProp(function () {
            return [
                'name' => 'Jonathan Reinink',
                'email' => 'jonathan@example.com',
            ];
        }),
    ],

    // Included on partial reload
    'billing' => [
        //
    ],

    // Not included on partial reload
    'data' => [
        //
    ],
];

Alternatively, you can define persistent properties globally in a middleware. These will be available on any request.

class HandleInertiaRequests extends Middleware
{
    protected $persisted = ['auth.user'];

    public function share(Request $request): array
    {
        return array_merge(parent::share($request), [
            'auth' => [
                'user' => new LazyProp(function () {
                    return [
                        'name' => 'Jonathan Reinink',
                        'email' => 'jonathan@example.com',
                    ];
                }),
            ],
        ]);
    }
}

Example use cases: