inertiajs / inertia-laravel

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

SSR with Dynamically Shared Props #572

Closed jringeisen closed 7 months ago

jringeisen commented 7 months ago

This might not be possible, but I was wondering if there is a way to setup SSR with dynamically shared props? I have two login portals, one for parents and another for the child. Depending on who is logged in (the parent or the child) we dynamically share props via the HandleInertiaRequests middleware. This currently doesn't work because obviously it doesn't know which data to load so it's loading an empty array. Checkout my code snippet below:

public function share(Request $request): array
{
    if ($request->user() instanceof \App\Models\User) {
        $values = new UserInertiaRequests();
    }

    if ($request->user() instanceof \App\Models\Student) {
        $values = new StudentInertiaRequests();
    }

    return [
        ...parent::share($request),
        isset($values) ? $values($request) : [],
        'ziggy' => fn () => [
            ...(new Ziggy)->toArray(),
            'location' => $request->url(),
        ],
    ];
}

I only need SSR on a couple frontend pages so that they can be indexed via search engines. I'm currently using a blade template to achieve this with some plain old javascript but ideally I'd like everything to use Inertia. Is there maybe a way to only apply SSR to certain pages?

jringeisen commented 7 months ago

🤦🏼‍♂️never mind, the issue was in my code. I needed to use the spread operator in order to merge the $values array.


public function share(Request $request): array
{
    $values = fn () => [];

    if ($request->user() instanceof \App\Models\User) {
        $values = new UserInertiaRequests();
    }

    if ($request->user() instanceof \App\Models\Student) {
        $values = new StudentInertiaRequests();
    }

    return [
        ...parent::share($request),
        ...$values($request),
        'ziggy' => function () use ($request) {
            return array_merge((new Ziggy)->toArray(), [
                'location' => $request->url(),
            ]);
        },
    ];
}