Detailed explanation of how to realize route function of Laravel in JS

  • 2021-07-21 05:54:47
  • OfStack

Everyone should know that in the routing module of Laravel, we can set a name for every route, such as:


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

Then you can pass through


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

To get the access address to this route, the back-end jump can be used


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

The advantage of this is that if there is an url change, for example, I want to put '/blog/{blog}' Change to '/boke/{blog}' You only need to change the routing file, and you don't need to adjust it anywhere else.

However, this is limited to the back end, and the blade template can be used. A slightly larger website will carry out the js file separately and will not write it directly in the blade template, which will lead to js sending ajax request or page jump. Only the request address can be written to death, for example


location.href = '/blog/' + id;

In this way, if the 10,000 route changes, it is necessary to modify the js file. If the same route is called by multiple js, it is easy to miss 1 or 2. So I consider whether I can implement a back-end route function in js.

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

The back-end part needs to implement 1 function


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

This function returns the original route address based on the route name, such as:


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

The front end also requires only one function:


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

Note: lodash is referenced here

The function does this:


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

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


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

In the js file, you can:


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

Summarize

The above is the whole content of this article. I hope the content of this article can bring 1 certain help to everyone's study or work. If you have any questions, you can leave a message for communication.


Related articles: