This is a 2-part technique to share named routes between Laravel and Javascript. It uses a custom artisan
command to export your named routes to JSON, and a Javascript route()
helper to lookup the route and fill in any parameters. Written for Laravel 5.3; not tested in 5.4.
Copy RouteJson.php
into your app as app/Console/Commands/RouteJson.php
Edit the app/Console/Kernel.php
file to make sure that Commands\RouteJson::class
is included in the $commands
array. For example, the $commands
in my Kernel.php
looks like this:
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
Commands\RouteJson::class
];
Copy route.js
into your app as resources/assets/js/route.js
Issue the command php artisan route:json
to export your routes to the file resources/assets/js/routes.json
. Then, in your Javascript code, you can import route from './route.js'
and use the route()
helper very similarly to the PHP version in Laravel:
import route from './route.js'; // or '../route.js', '../../route.js', etc
console.log( route( 'user.note.store', { user: 123 } )); // -> /user/123/note
Optional route parameters that aren't passed in the paramerter object will be discarded, but mandatory route parameters that aren't passed in will be left in the returned URI. No error or warning is generated if there are leftover mandatory parameters.
It's not perfect, but it's worked for me. Maybe it will work for you.
You just made my day 👍
Just one thing, in
generateRoutes
you use$route->getUri
this threw the folowing error in Laravel 5.4You should change it to $route->uri()`