Show name instead of id in url using laravel routing

I defined a route in laravel 4 that looks like this:

Route::get('/books/{id}', ' HomeController@showBook '); 

in url It shows / books / 1, for example, now I ask if there is a way to show the name of the book, and also save the identifier as a parameter in the route for SEO purposes.

early

+5
source share
2 answers

You can add as many URLs as you want, for example:

 Route::get('/books/{id}/{name}', ' HomeController@showBook '); 

Now that you want to create the URL of this page, you can do the following:

 URL::action(' HomeController@showBook ', ['id' => 1, 'name' => 'My awesome book']); 

Update:

If you are sure that there will never be two books with the same name, you can simply use the name of the book in the URL. You just need to do this:

 Route::get('/books/{name}', ' HomeControllers@showBook '); 

In your showBook function showBook you need to get the book from the database using name instead of id . I highly recommend using both an identifier and a name, because otherwise you might get into trouble because I don't think the book name will always be unique.

0
source

You can also do something like this:

 Route::get('books/{name}', function($name){ $url = explode("-", $name); $id = $url[0]; return "Book #$id"; }); 

So you can get the book by id if you pass the url: http://website.url/books/1-book-name

0
source

Source: https://habr.com/ru/post/1210646/


All Articles