#Is this good practice?
26 messages · Page 1 of 1 (latest)
Yes, if you need to share data globally, to every single page or for example a layout, you’d use the middleware to share data. Sharing user details is a typical thing to do
For example the Laravel starter kits take the same approach; https://github.com/laravel/vue-starter-kit/blob/main/app/Http/Middleware/HandleInertiaRequests.php#L47
Then you can access that data anywhere using the usePage() method
Should I make a new middleware or use the "HandleInertiaRequests" one?
Thanks
To answer that, I’d say: ask yourself, do you need a separate middleware for that? What sort of benefits would that bring for you/your app?
I see, maybe i'll just make a new one, so that I would not affect the prebuilt middleware
What would it “affect”? The middleware exists for that reason, otherwise it wouldn’t have been published to your app
I could use it for some other stuff tbh, who knows? I am just playing it safe, I guess.
@peak merlin Am I doing this correctly?
oh wait
I didn't use share
Aight fixed it
wait
I still don’t get why you need a separate middleware for that. Maybe it didn’t come across well, but with my question I tried to make you think about how it works and what the benefits would be. So, no, I wouldn’t use a separate middleware, the Inertia middleware is built to share global data, and from what I can tell, you don’t have a need for another middleware
No need controller
I see, but aside from that, are my usages of share" correct?
Yes, but I don’t see a reason to do so
aight, thanks btw, ima change it later.
Also I realized that they are basically the same thing lol
@peak merlin SInce usercount is only needed for my dashboard route, I grabbed the data from the controller. Is this the right way, right?
yes.
Adding shared values to HandleInertiaRequestMiddleware is an officially recommended way of doing what you’re trying to do
Thanks guys
I recently came across a case where three different routes needed access to some of the same data, and rendered the same React component in a sidebar, but those routes (and the associated data) were only accessible by users with a certain role so sharing the data globally made no sense.
I went with sharing using Inertia::share() in a middleware on the route group, and putting the relevant sidebar in a layout component used by the relevant page components.
I am not convinced it is the right solution now, as I am a little worried about indirection. I think just duplicating a couple of lines of code in each of the route handlers might be clearer.
In any case I am glad I explored the possibility. It is quite neat really. It feels similar to the route loader / outlet pattern in Remix / RRv6. I just wish the API was a little more self-evident so that when someone else reads it in 6 months they'd stand a better chance of immediately groking where the data is coming from.