Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

show name instead of id in a url using laravel routing

Tags:

laravel

routes

I have defined a route in laravel 4 that looks like so :

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

in the url It shows /books/1 for example , now i'm asking is there a way to show the name of the book instead but to keep also the id as a parameter in the route for SEO purposes

thanks in advance

like image 526
arakibi Avatar asked Jan 08 '15 08:01

arakibi


People also ask

How can I get route name in Laravel?

You may use the current, currentRouteName, and currentRouteAction methods on the Route facade to access information about the route handling the incoming request: $route = Route::current(); $name = Route::currentRouteName(); $action = Route::currentRouteAction();

How do I name a resource route in Laravel?

There are two ways you can modify the route names generated by a resource controller: Supply a names array as part of the third parameter $options array, with each key being the resource controller method (index, store, edit, etc.), and the value being the name you want to give the route.

Why do we use name in route in Laravel?

Named routes is an important feature in the Laravel framework. It allows you to refer to the routes when generating URLs or redirects to the specific routes. In short, we can say that the naming route is the way of providing a nickname to the route.


2 Answers

You could also do something like this:

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

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

like image 160
Alessandro Boselli Avatar answered Sep 16 '22 15:09

Alessandro Boselli


if your using laravel 8, this may be helpfull.
In your Controller add this

public function show(Blog $blog)
{
    return view('dashboard.Blog.show',compact('blog'));
}

In your web.php add this

Route::get('blog/{blog}', [\App\Http\Controllers\BlogController::class,'show'])->name('show');

Then add this to your model (am using Blog as my Model)

 public function getRouteKeyName()
{
    return 'title'; // db column name you would like to appear in the url.
}

Note: Please let your column name be unique(good practice).
Result: http://127.0.0.1:8000/blog/HelloWorld .....url for a single blog
So no more http://127.0.0.1:8000/blog/1
You are welcome.

like image 26
Arnoldkk Avatar answered Sep 16 '22 15:09

Arnoldkk