Using a url slug and id on the route

Published 1 week ago by codemode


I'm trying to put the slug and id on the URL.

So, i have a Post model, with basic things like id, title, description. (example - 1 , first-title, first description)... and i want the URL to look like

Route -

Route::get('{slug}_{id}', [email protected]');

Controller -

public function show(Post $id, $slug)
        return $id; //or compact into a view
              // and use str_slug() on the $title

I'm not sure if i need to store the slug into the database, also i'm not sure how the passing of values for $id and $slug should be.

Any help please? Thanks!


Why do you want to put the slug AND the id in the URL?


@topvillas - to avoid duplicate urls


If your using an auto increment id for your posts then they'll always be unique.


@topvillas - I understand. What i want to include is, the slug in the url.


A simple alternative would be to append/prepend the ID to the slug when you are generating/saving it.


$post->slug = $post->id . '-' . str_slug($post->title); 
// saved as 1-my-first-post

This solves your problem in the route since you can just do {slug} and don't have to worry about capturing the ID too

1 week ago (94,160 XP)

also i'm not sure how the passing of values for $id and $slug should be.

They're passed in the order that they appear in the route from left to right, so $slug first, then $id. So you have them reversed in your show(Post $id, $slug)


You can use this, it will generate the following:


str_slug($post->title . ' '. $post->id);

1 week ago (521,905 XP)

check this article for reasons why to have both, as well as a tutorial for implementation

Sign In or create a forum account to participate in this discussion.