Chris R.'s avatar

One route to many controllers

What is the best approach in this situation - I have e-commerce system where I want URL logic be like this:

  • www.example.com/en/product-1-slug
  • www.example.com/en/product-2-slug
  • www.example.com/en/category-1-slug
  • www.example.com/en/category-2-slug
  • www.example.com/en/category-1-slug/subcategory-1-slug
  • www.example.com/en/category-1-slug/subcategory-1-slug/subsubcategory-1-slug
  • www.example.com/en/some-static-page-slug
  • www.example.com/en/some-static-page-slug-2

etc.

So what I want is no extra "product" or "category" path. In this way its best for SEO. I already use mcamara/laravel-localization package and with language part is ok. But how to detect if slug is for product or category or static page and send laravel to right controller.

I have googled little bit and i founded few solutions:

  • Use one controller method to detect what slug it is and then redirect it to right controller:
public function getIndex()
{
    if(Auth::user()->isAdmin()) {
        //Admin
        return $this->getAdminIndex();
    } else {
        //No admin
        return $this->getUserIndex();
    }
}

protected function getAdminIndex()
{
    return view('admin.index');
}

protected function getUserIndex()
{
    return view('user.index');
}
  • Use different middlewares like this and in middleware check if its product or not, same with category and static page.
Route::group(['middleware' => 'IsProduct'], function () {
    Route::get('{slug}', 'ProductController@index');
});
0 likes
2 replies
aurawindsurfing's avatar

Hi,

I would reconsider if it is really better for SEO. I doubt it. For sure it is worse for you as a developer ;-)

I was trying to use mcamara but found it bit buggy, here is what I use for the same situation:

"arcanedev/localization": "^3.0",
"cviebrock/eloquent-sluggable": "^4.5",

And I use just regular controllers.

If you are focusing on SEO there is one big gotcha that you have to look for in Laravel. That is if you use Forge - all of the url's in your app are duplicated with index.php, Forge does not provide pretty url's out of the box.

Happy coding!

1 like
Mithrandir's avatar

Although I agree with @aurawindsurfing that the "it's better for SEO" argument is dubious, another way would be to have a catch-all route that looks up the slug, finds the right category of routes and then does an internal redirect with something like

return app()->call('App\Http\Controllers\ProductController@index');

Another way could perhaps be to have a catch-all route that has a middleware that modifies the request directly, to make it go to the Product, Category or Page controller...

But again, I think your approach will only cause you issues and I have no sources except rumors that it makes any difference for SEO.

2 likes

Please or to participate in this conversation.