[英]Laravel “root” route variable
I have the following routes in Laravel. 我在Laravel有以下路线。 I wanna be able to call both countries as well as pages on the "root" of the domain, not with any directory prefix.
我想能够调用这两个国家以及域“根”上的页面,而不用任何目录前缀。
What I want to achieve is that when no page is found in the eloquent model, that it tries to go open the country and if that fails as well then show a 404. 我想要实现的是,当雄辩的模型中找不到任何页面时,它将尝试打开该国家/地区,如果同样失败,则显示404。
Is that possible and what do I need to change? 那有可能吗,我需要改变什么?
Route::get('/{page}', 'PageController@view')->name('pages.view');
Route::get('/{country}', 'CountryController@view')->name('countries.view');
Edit: I think I was a bit unclear. 编辑:我想我有点不清楚。 The issue is, that the
countries.view
route is never reached because it fails before with pages.view
. 问题是,该
countries.view
路线永远达不到,因为它与之前失败pages.view
。 Let's say I call /germany
- it first matches the pages.view
route but no page germany
exists. 假设我叫
/germany
pages.view
它首先与pages.view
路由匹配,但没有germany
页面存在。 It immediately throws a 404 but I want it to check the country after that and only fail if /germany doesn't exist as a country as well. 它立即抛出404,但是我希望它在此之后检查该国家,并且仅在/ germany不存在作为国家的情况下才会失败。
How about being agnostic? 不可知论者如何? one route, you test the parameter, then returning the proper result.
一种方法是,测试参数,然后返回正确的结果。
Route::get('/{pageOrCountry}',function($pageOrCountry){
$page = App\Page::find($pageOrCountry);
if($page) return $page;
else $country = App\Country::find($pageOrCountry);
if($country) return $country;
else return redirect('404');
});
There are several ways I will mention two ways: 有几种方式,我将提到两种方式:
1- Route Model Binding : inside page controller create function 1-路由模型绑定:内部页面控制器创建功能
public function view(Page $page){
}
this function will return not found if page does not exists 如果页面不存在,此函数将返回找不到
2- Normal check : 2-正常检查:
public function view($page){
$check= Page::find($page);
if(!$check) abort(404);
}
创建resources / views / errors / 404.blade.php文件夹并定义404错误消息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.