简体   繁体   中英

Laravel Routing URL with two attributes

I have a City model and a Store model.

A Store belongs to a City and I would like the URL of a single Store to be like:

/<city-slug>/stores/<store-slug>

Example:

/nyc/stores/macys

This is what I have in the web.php :

Route::get('/{city}/stores/{store}', 'StoresController@show')->name('store');

The controller:

public function show($cityId, $storeId)
{
    $store = \App\Store::where('slug', $storeId)->first();

    return view('stores.show', compact('store'));
}

If I access /nyc/stores/macys it works but it also works if I replace nyc with any other string. I want only the URL with /nyc/stores/macys to be working. What am I missing? Thanks

My guess would be because you are only running a query on the store slug. You might try adding another where clause. Since Store belongs to City maybe try the following:

$city = City::where('slug', $cityId)->whereHas('stores', function ($query) use ($storeId) {
     $query->where('slug', $storeId);
})->get();

Then if you have a method on your City model called stores you could access that store data and return something like...

return view('stores.show)->with([ 'store' => $city->stores->first() ]);

I haven't tested this code myself, but hopefully it might help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM