JanYalda's avatar

Ziggy route filtering for Inertia app(react, laravel)

I've been attempting to filter out some routes that should only be visible to authenticated users, following the Ziggy docs I'm able to group the routes and use the @routes directive passing the group name in app.blade.php to only share those routes.

But where I'm having trouble is after logging in they don't change and I get Ziggy front-end errors until I refresh the page and I get the right routes then it works, this is what I initially thought would do it which is the following conditions in app.blade.php :

@auth
    @routes('authenticated')
@endauth
@guest
    @routes('guests')
@endguest

So what I'm wondering is if there is a way to dynamically send back the needed routes based on the auth check at the point where a user is logging in, or is this not possible?

0 likes
1 reply
LaryAI's avatar
Level 58

To dynamically send back the needed routes based on the authentication status, you can use a combination of Laravel's authentication middleware and the Ziggy package.

First, make sure you have the Ziggy package installed and properly configured in your Laravel application.

Next, you can create two separate route files for authenticated and guest users. For example, you can create a file called web.php for authenticated users and guest.php for guest users.

In your web.php file, define the routes that should only be visible to authenticated users. Similarly, in your guest.php file, define the routes that should only be visible to guest users.

Here's an example of how your web.php file might look like:

<?php

use Illuminate\Support\Facades\Route;

Route::middleware('auth')->group(function () {
    // Authenticated routes
    // ...
});

And here's an example of how your guest.php file might look like:

<?php

use Illuminate\Support\Facades\Route;

Route::middleware('guest')->group(function () {
    // Guest routes
    // ...
});

Now, in your app.blade.php file, you can conditionally include the appropriate route file based on the authentication status using the @routes directive:

@auth
    @routes('web')
@endauth

@guest
    @routes('guest')
@endguest

Make sure to update the @routes directive with the appropriate group name that matches your route file names.

By doing this, the routes will be dynamically included based on the authentication status of the user. When a user logs in or logs out, the routes will be updated accordingly.

Remember to clear your route cache by running php artisan route:cache after making these changes.

I hope this helps! Let me know if you have any further questions.

Please or to participate in this conversation.