2017-06-18 154 views
0

我只是做了這個,但/maps/{category}/{map}無法正常工作。路由參數laravel問題

將任何東西放在{category}顯示相同的結果。

/maps/php/1 
/maps/laravel/1 

我想顯示一個結果,當類別的名稱和地圖的ID完全匹配,否則重定向到主頁。

我的路線

Route::get('/maps/{category}', '[email protected]'); 
Route::get('/maps/{category}/{map}', '[email protected]'); 

我控制器

public function show(Category $category, Map $map) 
{   
    return view('maps.show', compact('map')); 
} 

我的刀模板

{{ $map->title }} 

回答

0
Route::get('/maps/{category}', '[email protected]'); 

是一個更廣義的路徑,使其符合以上

Route::get('/maps/{category}/{map}', '[email protected]'); 

你應該首先列出顯示路線。

要匹配確切的模型屬性(即名稱),您應該自定義路由器在路由服務提供程序引導方法中使用的解析邏輯。例如:

Route::bind('category', function ($value) { 
    return App\Category::where('name', $value)->first(); 
}); 
Route::bind('map', function ($value) { 
    return App\Map::where('id', $value)->first(); 
}); 
0

首先,有沒有必要,如果你使用的是5.4,交換路由的順序,因爲我開始用5.4使用laravel我不能說以前的版本什麼。

如果你想過濾被問及的地圖是否符合給定的類別,如果你定義了類別和地圖之間的關係,你可以使用「whereHas」方法與雄辯。

「一對多(倒數)」的關係是你需要使用的東西,查看這裏:https://laravel.com/docs/5.4/eloquent-relationships#one-to-many-inverse

和查詢的關係是你需要知道什麼,點擊這裏:https://laravel.com/docs/5.4/eloquent-relationships#querying-relationship-existence

怎樣的關係應該看起來像地圖模型:

/** 
* Get the category that owns the map. 
*/ 
public function category() 
{ 
    return $this->belongsTo('App\Category'); 
} 

一個例子代碼:

public function show($category, $map) 
{   
    $map = Map::whereHas('category',function($query) use($category){ 
     $query->where('id', $category); 
    }); 

    return view('maps.show', compact('map')); 
}