0

We have 3 types of urls:

  • Countries like: /germany-travel or /united-kingdom-travel
  • Cities like: /berlin or /los-angeles
  • Artikles like: /my-great-article or /my-other-great-article

To separete these 3 types of urls, I need a working routing in laravel, based on slugs on my 3 database models Country, City and Article.

// Country
Route::get('{country}-travel', function(\App\Models\Country $country){
    return view('country.show', ["object" => $country]);
});

// City
Route::get('{city}', function(\App\Models\City $city){
    return view('city.show', ["object" => $city]);
})->where("city", "[a-z-]+");

// Articles
Route::get('{article?}', function(\App\Models\Article $article){
    return view('article.show', ["object" => $article]);
}))->where('article', '.*');

This only works for countries and cities, since '/my-great-article' is also treated as city (and because of this, I get an 404 not found, since there is no city with "my-great-article" slug. Any ideas?

bernhardh
  • 3,137
  • 10
  • 42
  • 77
  • Possible duplicate of [Single Laravel Route for multiple controllers](https://stackoverflow.com/questions/31368433/single-laravel-route-for-multiple-controllers) – Ron van der Heijden Jun 15 '18 at 14:36
  • Yeah, this would be inefficient even if it did work as you'd potentially have to evaluate every route just to determine which one fits the "best". I'd recommend using a prefix for cities and articles. – Devon Bessemer Jun 15 '18 at 14:36
  • @Devon: Maybe, but its an existing project from another framework and I don't wanna lose existing urls in Google index – bernhardh Jun 15 '18 at 14:38
  • 1
    Then I'd recommend the duplicate solution. Use a single route and controller that does the lookup and returns the corresponding view. – Devon Bessemer Jun 15 '18 at 14:39
  • The URL pattern above is just wonky, and it's not maintainable. Use proper `301` URL redirection to maintain SEO and prefix things with `/cities/{city}` and `/articles{/{article}` for instance. – Ohgodwhy Jun 15 '18 at 14:43
  • @Ohgodwhy: Not, its not. In the Cities table, there are only ~50 Cities, so there is just a simple select-query on a very small table - not a dealbreak. The urls are defined by customer and have to be as they are and as they where – bernhardh Jun 15 '18 at 14:48
  • @Devon: Thanks you for your hint – bernhardh Jun 15 '18 at 14:48
  • Okay, you're right, the URL pattern above isn't wonky. ¯\_(ツ)_/¯ – Ohgodwhy Jun 15 '18 at 14:49

0 Answers0