简体   繁体   中英

Laravel “root” route variable

I have the following routes in 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.

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 . Let's say I call /germany - it first matches the pages.view route but no page germany exists. 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.

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

  public function view(Page $page){
   }

this function will return not found if page does not exists

2- Normal check :

   public function view($page){
    $check= Page::find($page);
     if(!$check) abort(404);
   }

创建resources / views / errors / 404.blade.php文件夹并定义404错误消息

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM