I want to SEO-up my laravel URLs, so I want to change www.example.com/posts/32
to www.example.com/posts/how-to-name-routes
I see that I can manually name routes by chaining the name()
method on the route, but I want the name
to be automatically filled from the title of the post. The titles, however, contain spaces So my Post
object would have the title
'How to name routes'
but the URL would be www.example.com/posts/how-to-name-routes
Do I need to implement my own string manipulation system or is this something Laravel handles already?
2
Answers
You could add a unique slug column for your Posts table and then use that as the parameter in your routes e.g.
'/posts/{slug}'
.You can add a mutator for this inside your Post model:
My recommendation would be to implement a slug field on your
Post
model and use that as the key for Route Model Binding.To slugify the post title, use Laravel’s Muttators to convert the post title to a URL friendly slug.
To ensure that slugs are unique, you can append the timestamp to the slug, preserving SEO while removing conflicts on the column.
After creating a slug field, you can bind it to the route by overriding the
getRouteKeyName
method in yourPost
model.Your routes will become something like
References:
Route Model Binding:
https://laravel.com/docs/5.8/routing#route-model-binding
Slug Helper:
https://laravel.com/docs/5.8/helpers#method-str-slug
Eloquent Mutators:
https://laravel.com/docs/5.8/eloquent-mutators