Ziggy creates a Blade directive which you can include in your views. This will export a JavaScript object of your application's named routes, keyed by their names (aliases), as well as a global route()
helper function which you can use to access your routes in your JavaScript.
-
Add Ziggy to your Composer file:
composer require tightenco/ziggy
-
(if Laravel 5.4) Add
Tightenco\Ziggy\ZiggyServiceProvider::class
to theproviders
array in yourconfig/app.php
. -
Include our Blade Directive (
@routes
) somewhere in your template before your main application JavaScript is loaded—likely in the header somewhere.
This package replaces the @routes
directive with a collection of all of your application's routes, keyed by their names. This collection is available at window.namedRoutes
.
The package also creates an optional route()
JavaScript helper which functions like Laravel's route()
PHP helper, which can be used to retrieve URLs by name and (optionally) parameters.
For example:
route('posts.index')
should return posts
If you wish to retrieve the URL for a route with required parameters, pass a JavaScript object with the parameterss as the second argument to route()
:
route('posts.show', {id: 1})
should return posts/1
Here's a full example:
let postId = 1337;
return axios.get(route('posts.show', {id: postId}))
.then((response) => {
return response.data;
});
Thanks to Caleb Porzio, Adam Wathan, and Jeffrey Way.