Using a url slug and id on the route

Published 1 week ago by codemode

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}', [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!

topvillas

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

codemode

@topvillas - to avoid duplicate urls

topvillas

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

codemode

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

Demers94

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
Cronix
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)

webmind

You can use this, it will generate the following:

welcome-to-my-blog-1

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

Snapey
Snapey
1 week ago (521,905 XP)

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

https://sebastiandedeyne.com/posts/2017/non-breaking-seo-friendly-urls-in-laravel

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