Created
September 4, 2019 18:28
-
-
Save farshidrezaei/4c9ca99e17524a00b9ba0be63782618b to your computer and use it in GitHub Desktop.
Use Laravel named routes in Vuejs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
window.Laravel = @json([ | |
'csrfToken' => csrf_token(), | |
'baseUrl' => url('/'), | |
'routes' => collect(Route::getRoutes()) | |
->mapWithKeys(function ($route) { | |
return [ | |
$route->getName() => $route->uri() | |
]; | |
}) | |
]); | |
</script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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('/'); | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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