2017-09-19 22 views
0

我有一個City模型和一個Store模型。具有兩個屬性的Laravel路由URL

一個Store屬於City,我想一個Store的URL是這樣的:

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

例子:

/nyc/stores/macys

這是我在web.php

Route::get('/{city}/stores/{store}', '[email protected]')->name('store');

控制器:

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

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

如果我訪問/nyc/stores/macys它的工作原理,但它也可以,如果我與其他任何字符串替換nyc。我只想要/nyc/stores/macys正在工作的網址。我錯過了什麼?謝謝

+0

在您的查詢過濾器中只適用於$ storeId而不是$ cityId。您可以對$ cityId應用相同的限制其訪問權限 –

回答

0

我的猜測會是因爲你只是在商店slug上運行一個查詢。您可以嘗試添加另一個where子句。由於Store屬於City也許嘗試以下操作:

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

然後,如果你有一個方法對你City模式叫stores你可以訪問存儲數據並返回類似...

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

我我自己沒有測試過這個代碼,但希望它可以幫助你。