How to filter Ziggy routes injected into InertiaJS based on user permissions in Laravel?

I'm working on a Laravel project using InertiaJS and ReactJS. To inject routes into my frontend, I'm using Ziggy routes. However, I also have the Spatie/Laravel-Permissions package installed.

The issue is that Ziggy injects all routes into the frontend, which can potentially lead to security vulnerabilities. I want to filter the injected routes so that only routes the user has permission to access are included. For example, all client routes should be accessible, but for the admin dashboard, only specific routes should be available based on permissions.

All of my routes have names defined like client.* and admin.* . I also have fortify routes, horizon routes and debugbar routes.

What's the best way to achieve this?

HandleInertiaRequests.php middleware:

public function share(Request $request): array
    {
        return [
            ...parent::share($request),
            'auth' => [
                'user' => $request->user(),
                'roles' => Auth::check() ? Auth::user()->getRoleNames() : [],
                'permissions' => Auth::check() ? Auth::user()->getAllPermissions() : [],
            ],
            'flash' => function () use ($request) {
                return [
                    'success' => $request->session()->get('success'),
                    'error' => $request->session()->get('error'),
                ];
            },
            'ziggy' => fn () => [
                ...(new Ziggy)->toArray(),
                'location' => $request->url(),
            ],
            'csrf_token' => csrf_token(),
        ];
    }

Upvotes: 2

Views: 79

Answers (0)

Related Questions