Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

codemode's avatar

Using a url slug and id on the route

Hello,

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 www.website.com/first-title_1

Route -

Route::get('{slug}_{id}', 'PostsController@show');

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!

0 likes
9 replies
topvillas's avatar

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

topvillas's avatar

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

Demers94's avatar
Demers94
Best Answer
Level 13

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

Ex:

$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

Cronix's avatar

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)

webmind's avatar

You can use this, it will generate the following:

welcome-to-my-blog-1

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

Please or to participate in this conversation.