Skip to content

Instantly share code, notes, and snippets.

@eaguad1337
Last active April 12, 2017 13:41
Show Gist options
  • Save eaguad1337/b6525053ed9369ce573f85f5af39a446 to your computer and use it in GitHub Desktop.
Save eaguad1337/b6525053ed9369ce573f85f5af39a446 to your computer and use it in GitHub Desktop.
JS script to resolve laravel routes
// Eduardo Aguad - eaguad[at]meat[dot]cl
var LaraHelper = new function() {
var routes = null;
this.syncRoutes = function() {
$.ajax({
url: '/api/routes',
dataType: 'json',
success: function(result) {
routes = result;
}
});
}
this.route = function (route, params) {
let routePath = null;
let result = null;
let routeKey = Object.keys(routes).filter(function(key, val) {
return routes[key].route == route;
});
if(typeof routes[routeKey[0]] != 'undefined') {
routePath = routes[routeKey[0]].path;
} else {
throw 'Route does not exist or is not public';
}
let matches = routePath.match(/{\w+}/g);
if(matches) {
if(!Array.isArray(params)) {
throw 'Parameter 2 must be an array';
}
if(params && matches.length != params.length) {
throw 'Parameters needed: ' + matches.length;
} else {
for(let i = 0; i < matches.length; i++) {
routePath = routePath.replace(/{\w+}/, params[i]);
}
}
}
return routePath;
}
this.syncRoutes();
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Route;
class LaraHelperController extends Controller
{
public function getRoutes() {
$publicRoutes = [
'article.detail',
'article.list'
];
$routes = Route::getRoutes();
$result = null;
foreach($routes as $route) {
$result[] = [
'route' => $route->getName(),
'path' => $route->getPath(),
];
}
$routes = array_filter($result, function($value) use ($publicRoutes) {
return in_array($value['route'], $publicRoutes);
});
return $routes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment