路由优先顺序 [英] Route precedence order

查看:390
本文介绍了路由优先顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2条路由,它们的方法写在同一控制器中[LinkController]:

I have 2 routes with their methods written in same controller[LinkController]:

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

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

我的方法是:

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是否具有路由优先级?

The trouble i am having is the second route [single.tour] returns the view of the first route [tour.list]. I tried to return other view also in 2nd method but still it returns the view of first method. Does laravel have routing precedence ?

推荐答案

您的两条路线均在同一位置包含两个参数.这意味着与路由1匹配的所有url也将与路由2匹配.无论您将它们放在路由定义中的顺序如何,所有请求都将始终转到相同的路由.

Both your routes consist of two parameters in the same place. That means any url that matches route 1 will also match route 2. No matter in what order you put them in your routes definition, all requests will always go to the same route.

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

To avoid that you can specify restrictions on the parameters using regular expressions. For example, the country parameter may only accept two letter country codes, or the category parameter may have to be a numeric 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

这篇关于路由优先顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆