2016-12-06 147 views
1

我有2种途径与他们的方法写在同一个控制器[LinkController]:路由优先级顺序

Route::get('/{country}/{category}', ['as' => 'tour.list', 'uses' => '[email protected]']); 

Route::get('/{category}/{slug}',['as' => 'single.tour', 'uses' => '[email protected]']); 

而且我的方法是:

public function tourlist($country, $category) 
{ 
    $tour = Tour::whereHas('category', function($q) use($category) { 
      $q->where('name','=', $category); 
     }) 
     ->whereHas('country', function($r) use($country) { 
      $r->where('name','=', $country); 
     }) 
     ->get(); 
    return view('public.tours.list')->withTours($tour); 
} 
public function singleTour($slug,$category) 
{ 
    $tour = Tour::where('slug','=', $slug) 
       ->whereHas('category', function($r) use($category) { 
      $r->where('name','=', $category); 
     }) 
     ->first(); 
    return view('public.tours.show')->withTour($tour); 
} 

我的视图代码是:

<a href="{{ route('single.tour',['category' => $tour->category->name, 'slug' => $tour->slug]) }}">{{$tour->title}}</a> 

我遇到的麻烦是第二条路线[single.tour]返回第一条路线[tour.list]的视图。我试图在第二种方法中返回其他视图,但仍返回第一种方法的视图。 laravel有路由优先权吗?

+0

烨,后者将优先考虑http://stackoverflow.com/questions/20870899/order-of-route-declarations-in-laravel-package – SteD

回答

0

这是因为发生的事情,Laravel比赛路线从文件,并较早来得快,匹配模式将首先执行,你可以使用正则表达式的技术来避免这一类的路线:

Route::get('user/{name}', function ($name) { 
    // 
})->where('name', '[A-Za-z]+'); // <------ define your regex here to differ the routes 

Laravel Routing Docs

希望这会有所帮助!

+0

是很好的建议,使用' - >哪里()'更明确...... – Kyslik

0

您的路线都包含两个参数在同一个地方。这意味着任何匹配路由1的URL都将匹配路由2.无论按照什么顺序将它们放入路由定义中,所有请求都将始终转到相同的路由。

为了避免这种情况,您可以使用正则表达式对参数指定限制。例如,country参数可能只接受两个字母的国家/地区代码,或者category参数可能必须是数字ID。

Route::get('/{country}/{category}') 
    ->where('country', '[A-Z]{2}') 
    ->where('category', '[0-9]+'); 

https://laravel.com/docs/5.3/routing#parameters-regular-expression-constraints

+0

根据你的建议,我修改了我的路线:'Route :: get('/ {country}/{category}',''as'=>' tour.list','uses'=>'LinkController @ tourlist']) \t \t \t \t - > where('country','[A-Za-z] +') - > where('category',' [A-Za-z] +');'和'Route :: get('/ {category}/{slug}',['as'=>'single.tour' , '使用'=> 'LinkController @ singleTour']) \t \t \t \t - >其中( '类别', '[A-ZA-Z] +') - >其中( '类别',“[W \ d \');'';'我得到这个错误'Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException' –

+0

你试过什么网址? – LorenzSchaef

+0

现在解决了这个问题。 –