SoFunction
Updated on 2025-04-08

Detailed explanation of how to implement Laravel's route function in JS

Everyone should know that in Laravel's routing module, we can set a name for each route, such as:

Route::get('/blog/{blog}', 'BlogController@show')->name('')

Then you can pass

route('', ['blog' => 1])

To get the access address of this route, you can use the backend jump

return redirect()->route('', ['blog' => 1]);

The advantage of doing this is that if the url changes occur, for example, I want to'/blog/{blog}'Change to'/boke/{blog}', you only need to change the routing file, and you don’t need to adjust it elsewhere.

However, this is limited to the backend and blade templates. Websites with a slightly larger scale will take out the js file separately and will not be written directly in the blade template. This will result in the request address being written to death when sending ajax request in JS or when the page jumps. For example,

 = '/blog/' + id;

In this way, if the route changes, you have to modify the js file. If the same route is called by multiple js, it is still easy to miss one or two changes. So I'm considering whether I can implement a backend-like route function in js.

The final solution is very simple, just two functions are done.

The backend part needs to implement a function

function route_uri($name)
{
 return app('router')->getRoutes()->getByName($name)->getUri();
}

The function of this function is to return the original route address based on the route name, for example:

echo route_uri(''); // Will output/blog/{blog}

The front-end also only needs one function:

let route = (routeUrl, param) => {
 let append = [];
 for (let x in param) {
  let search = '{' + x + '}';
  if ((search) >= 0) {
   routeUrl = ('{' + x + '}', param[x]);
  } else {
   (x + '=' + param[x]);
  }
 }
 let url = '/' + _.trimStart(routeUrl, '/');
 if ( == 0) {
  return url;
 }
 if (('?') >= 0) {
  url += '&';
 } else {
  url += '?';
 }
 url += ('&');
 return url;
}

Note:Lodash is referenced here

The function of this function is:

route('/blog/{blog}', {blog: 1}); //Return /blog/1route('/blog/{blog}', {blog: 1, preview: 1}); //return /blog/1?preview=1

Then it's very simple, define it in the blade template:

var routes = {
 blog: {
  show: '{{ route_uri('') }}',
  update: '{{ route_uri('') }}',
  destroy: '{{ route_uri('') }}'
 }
};

In the js file, you can:

$.post(route(, {blog: 1}), {title: 'xxx', content: 'xxx'})

Summarize

The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate.