How to Use Laravel Routes in Javascript
Andrei Canta
795

Here is an improved version of js function: it works with multiple parameters such as

p/{id}/some-category/{catId}/some-item/{itemId}

usage: route(‘myroute.with.many.params’,[2,3,2])

other change is that even for a single param there must be used as [2]

var routes = require('./routes.json');


exports.route = function() {
var args = Array.prototype.slice.call(arguments);
var name = args.shift();
var routeParams = args.shift();

if (routes[name] === undefined) {
console.error('Unknown route. Try to export the latest.', name);
} else {

var n = 0;
return routes[name].replace(/({\w+})/g, function(i) {

var r = routeParams[n++];

if(undefined == r){
console.error('The parameter no. ' + n + ' is missing from route parameters' );
}

return r;
});

}

};
Like what you read? Give D a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.