Home » vue » Global Variable in Javascript for Laravel Routes – Is this a good idea?

Global Variable in Javascript for Laravel Routes – Is this a good idea?

Posted by: admin November 26, 2021 Leave a comment

Questions:

I’ve created some code using a View Composer where I am passing my Route Collection through to the front end on all views, so I can access all of my laravel routes in Vuejs via the route named associated with them.

For example, to upload an image using a vue component, instead of passing my upload route into the Vue Component, it is listed as a part of a global variable:

var uploadRoute     = _.find(globalRoutes, function(route) { return route.name == 'route-name.image.upload' });
$.post(uploadRoute, data) ... etc

My question is…is this sensible? I’m publically publishing my entire app’s routes.

Thanks

Answers:

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.