Skip to content

Instantly share code, notes, and snippets.

@farshidrezaei
Created September 4, 2019 18:28
Show Gist options
  • Save farshidrezaei/4c9ca99e17524a00b9ba0be63782618b to your computer and use it in GitHub Desktop.
Save farshidrezaei/4c9ca99e17524a00b9ba0be63782618b to your computer and use it in GitHub Desktop.
Use Laravel named routes in Vuejs
<script>
window.Laravel = @json([
'csrfToken' => csrf_token(),
'baseUrl' => url('/'),
'routes' => collect(Route::getRoutes())
->mapWithKeys(function ($route) {
return [
$route->getName() => $route->uri()
];
})
]);
</script>
// import this file in window.route like this:
// import route from './route.js';
// window.route=route;
var routes = window.Laravel.routes;
module.exports = function () {
var args = Array.prototype.slice.call(arguments);
var name = args.shift();
if (routes[name] === undefined) {
console.error('Route not found ', name);
}
else {
return window.Laravel.baseUrl
+ '/'
+ routes[name]
.split( '/' )
.map( s => {
s[0] === '{' ? args.shift() : s
} )
.join('/');
}
};
route(‘post.index’); // "http://example.com/posts"
let post={
id:1,
title:'Post 2'
}
route(‘post.update’, this.post.id); // "http://example.com/posts/1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment