Skip to content

How I Like to Simplify Ziggy’s Route Helper

If you’re not already familiar with Tighten’s package Ziggy, it makes it simple to use the routes you define in Laravel in your JavaScript.

Little Goat Boy with a blue mohawk and its tongue sticking out.

Jamming good with Weird and Gilly | Photo by George Potter on Unsplash

If you’re not already familiar with Tighten’s package Ziggy, it makes it simple to use the routes you define in Laravel in your JavaScript. It’s a great package, but I prefer to use it a little differently than they outline in their docs.

All I really want from Ziggy is to be able to use a helper in my JS to get a URL, the exact same way as Laravel’s route helper. For example, if I want the URL for an API endpoint that lists all users, I just want to drop route('api.user.show', [userId]) in my JavaScript to get /api/users/1 back.

I want not to do any of the following:

  • Use the @routes Blade directive (perhaps a bit purist of me, but I don’t like how it dumps all the route info as inline JavaScript).

  • Commit compiled files to git (the route helper returns absolute URLs with your APP_URL leading the way).

  • Call any other methods Ziggy’s route helper provides.

Thankfully, configuring things as I prefer is fairly straightforward. All I did was:

  1. update my node scripts to use Ziggy’s Artisan command,

  2. add the output file to my .gitignore, and

  3. define my own route helper that relies on Ziggy’s.

1. Tweak yer scripts.

Laravel’s default package.json looks something like this:

I need a routes file generated separately in all environments before compiling my JavaScript, so I added a script for that and call it in my development and production scripts.

2. Withhold attention.

.gitignore:

/resources/js/routes.js

¯\(ツ)

3. Tell that route helper what’s up.

global-helpers.js:

The generated routes.js exports the routes in an object named Ziggy, which is what we’re importing on line 2 and passing as the 4th argument to ZiggyRoute(). The third argument tells Ziggy whether to use absolute URLs.

In app.js, I can just drop import 'global-helpers'; in and call my stripped-down route helper anywhere.

NOTE: I’ve got this in my webpack.mix.js (lets me import from vendor):

That’s it.

If you run into snags with ESLint or Jest, hit me up and I can share more of the less-directly-relevant setup.

You might also like