In this series is covered getting data by other than id. The example uses tags: https://laracasts.com/series/laravel-6-from-scratch number 31 and 32.
Dynamic urls and getting data from multiple tables
Hi, I'm very new to laravel and mysql aswell.
I'm trying to create urls like this: /Afrika/Egypte/Cairo/Cairo-International-Airport.
In my web.php i have set a route like this: Route::get('{continent}/{country}/{city}/{airportname}
/airports -> lists all airports /{continent}/{country} -> list of airports in that country /{continent}/{country}/{city} -> list of airports in that city /{continent}/{country}/{city}/{airport} -> shows airport info of that specific airport
I have set up 3 tables. A
- countries table (id, countryName, slug and continent).
- cities table (id, cityName, slug, country_id)
- airports table (id (primary), airportName, slug, city_id (foreign) and country_id (foreign))
In my controller i have this for the single airport:
public function show($continent, $country, $city, $airportname)
{
$airport = Airport::where('slug', $airportname)->first();
return view('airports.show', ['airport' => $airport], compact('continent', 'country', 'city', 'airportname'));
}
This works ok, but when i add an airport to the url that does not match the city or country it will work to. It should be linked to the city_id or something like that. But i dont know how to make that work. Same for list of of airport when the end of the url is a city. I want to show the cityname and not an id in the url, but i only want to list the airports that belongs to that specific city.
My Airport model looks like this:
public function path() { return route('airports.show', this); }
public function city() { return $this->belongsTo(City::class); }
public function country() { return $this->belongsTo(Country::class); }
Please or to participate in this conversation.