Brainmaniac
Brainmaniac

Reputation: 2536

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.

Upvotes: 0

Views: 879

Answers (2)

Dorin Puscasu
Dorin Puscasu

Reputation: 1

Route::get('/test/{slug1}/{slug2}','IndexController@index');

public function index($slug1, $slug2)
{
   $id_slug =  last(explode('-',$slug2));

   $second_slug = str_replace('-'.$id_slug,'',$slug2);

   dd($slug1, $second_slug,$id_slug);
}

Upvotes: 0

Tim Lewis
Tim Lewis

Reputation: 29257

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.

Upvotes: 1

Related Questions