Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Brian Kidd's avatar

Additional user data with Jetstream Inertia request user shared data

Jetstream adds the user to the shared data and I would like to add additional data to that user. Looking at the Jetstream service provider, I would think the Jetstream provided data would already be in the shared data but if I dd(parent::share($request)) in HandleInertiaRequests middelware, only the default error property is there but no Jetstream data. If I try to send the 'user' key, it gets overwritten by Jetstream shared data. What am I missing? I know I could add an accessor to the user model but I don't need this data for all users, just the authenticated user. Thanks

0 likes
3 replies
vincent15000's avatar

You can add an custom attribute and load it only if you need to load it.

// if you declare this new attribute in the ```$attributes``` array, it will be loaded with each API answer
protected $attributes = ['my_new_message'];

// necessarily in both cases (declare or not above)
public function getMyNewMessageAttribute()
{
	return 'hello';
}

If you don't declare it in the $attributes array, you can access it manually : each time you need it, it will call the public function to get the content of the variable.

$model->my_new_message;

If you are using API resources, you can ever decide to load the property for the authenticated users.

'my_new_message' => $this->when(auth()->user(), $this->my_new_message),

https://laravel.com/docs/10.x/eloquent-resources#conditional-attributes

mchev's avatar
mchev
Best Answer
Level 2

You can also merge the shared data provided by Jetstream in the HandleInertiaRequest Middleware :

        $jetstreamAuthUser = Inertia::getShared('auth.user');

        return array_merge(parent::share($request), [
            'auth' => [
                'user' => function () use ($jetstreamAuthUser, $request) {
                    return $request->user() ? array_merge($jetstreamAuthUser(), [
                        'attribute' => $request->user()->attribute,
                    ]) : null;
                },
            ]
        ]);
2 likes

Please or to participate in this conversation.