Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

Construct routes(urls) with slugs separated by dash in laravel

I am about to make more SEO-friendly URLs on my page and want a pattern looking like this for my products:

www.example.com/product-category/a-pretty-long-seo-friendly-product-name-12

So what are we looking at here?

www.example.com/{slug1}/{slug2}-{id}

The only thing I will care about from the URL in my controller is the {id}. The rest two slugs are just of SEO purpose. So to my question. How can I get the 12 from a-pretty-long-seo-friendly-product-name-12?

I have tried www.mydomain.com/{slug}/{slug}-{id} and in my controller to try and get $id. Id does not work. I am not able to able to separate it from from a-pretty-long-seo-friendly-product-name. So in my controller no matter how I do I get {slug2} and {id} concatenated.

Coming from rails it is a piece of cake there but can't seem to figure out how to do that here in laravel.

EDIT: I am sorry I formulated my question very unclear. I am looking for a way to do this in the routes file. Like in rails.

question from:https://stackoverflow.com/questions/65852115/construct-routesurls-with-slugs-separated-by-dash-in-laravel

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're on the right track, but you can't really logically separate /{slug}-{id} if you're using dash-separated strings. To handle this, you can simply explode the chunks and select the last one:

// routes/web.php
Route::get('/{primarySlug}/{secondarySlugAndId}', [ExampleController::class, 'example']);

// ExampleController.php
public function example($primarySlug, $secondarySlugAndId){
  $parts = collect(explode('-', $secondarySlugAndId));
  $id = $parts->last();
  $secondarySlug = $parts->slice(0, -1)->implode('-');

  ... // Do anything else you need to do
}

Given the URL example.com/primary-slug/secondary-slug-99, you would have the following variables:

dd($primarySlug, $secondarySlug, $id);
// "primary-slug"
// "secondary-slug"
// "99"

The only case this wouldn't work for is if your id had a dash in it, but that's another layer of complexity that I hope you don't have to handle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...