[Vuejs]-Global Variable in Javascript for Laravel Routes – Is this a good idea?

2👍

I think your hunch about exposing your entire apps routes is legit. IMO you should explicitly pick out the routes that you need. So in thise case, you should only expose route-name.image.upload. You could create a tiny helper function to look up routes and output them along with the URL as JSON.

function json_routes(array $routes)
{
   $return = [];

   foreach($routes as $route)
   {
       $return[$route] = route($route);
   }

   return new \Illuminate\Support\HtmlString(json_encode($return));

}

And the, in your main view:

var routes = {{ json_routes(["route-name.image.upload"]) }};

Getting a route is simple:

routes['route-name.image.upload']; 

This is the most basic exaple I can think of. You can optimize it quite a bit. Just some ideas:

  • Place the routes in a central place, fx. a config element: json_routes(config('app.json_routes'))
  • Build a command that generates a static .json file so that you don’t iterate through the routes on each page load. Remember to re-generate when you add more routes.
  • Create a function instead of an object to get the route. That allows you to build in logic and gives a more Laravel-like feel in your js: function route(path){ return window.routes.hasOwnProperty(path) ? window.routes[path] : null ;}

  • (Advanced) Re-write Laravels router logic and hook into the options array, allowing you to do something like Route::get('dashboard', '...', ['as'=>'dashboard', 'expose'=>true]);, then dynamically generate the before mentioned json-file on all routes with the expose option.

👤rdiz

Leave a comment