laravel 如何检查路由“URL”是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36133535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 13:27:10  来源:igfitidea点击:

How can I check whether the route "URL" exists?

phplaravelroutes

提问by u775856

In Laravel 5.2, is there a particular way (handler) to check whether a route is existing or not? Let's say, for a basic URL like:

Laravel 5.2 中,是否有特定的方法(处理程序)来检查路由是否存在?比方说,对于一个基本的 URL,如:

http://www.example.com/laravel

I then want to handle the non-existing URLs (like: /laravel) from my Main Page Router, which is:

然后我想处理/laravel来自我的 Main Page Router的不存在的 URL(如:),它是:

Route::get('/{page}', funtion(){
    //check if $page is a valid route URL? Or 404?
});

How do I purposely check whether this route is a valid one or not?

我如何有目的地检查这条路线是否有效?

回答by Pitchinnate

Simply put your Route::get('/{page}','MainController@getPage');last. That way if it finds another route before it will use it but if it doesn't then it will get caught by this. For example:

简单地把你的Route::get('/{page}','MainController@getPage');最后。这样,如果它在使用它之前找到另一条路线,但如果没有,那么它就会被它抓住。例如:

Route::get('/welcome','WelcomeController@getWelcome');
Route::get('/test','TestController@getTest');
Route::get('/{page}','MainController@getPage');

If you were to hit /welcomeor /testit should route them to the correct controller. If you where to hit /helloit should go to the MainControllerand hit function getPage($page)with $pagebeing the page you hit.

如果您要击中/welcome/test应该将它们路由到正确的控制器。如果你在哪里打/hello它应该去MainController和命中功能getPage($page)$page被你打的页面。

If it hits MainController@getPageyou know it was basically a 404.

如果它命中,MainController@getPage你就会知道它基本上是一个 404。

If you need to know before you hit the route for some reason you could create something like this:

如果您出于某种原因需要在到达路线之前知道,您可以创建如下内容:

Route::get('/checkurl/{page}',function($page) {
    $exists = Route::has('/' . $page);
    return (new Response(json_encode(['exists'=>$exists]),200);
});

回答by user2094178

I use the following as my last route:

我使用以下作为我的最后一条路线:

Route::any('{catchall}', function($page) {
    abort(404);
} )->where('catchall', '(.*)');

If you are not aware yet, abort(404)will return the view 404.blade.phpfrom resources/views/errors.

如果你不知道的是,abort(404)将返回视图404.blade.phpresources/views/errors

回答by TGA

Adding last route with any catch doesn't works anymore with laravel 5.5.1+

使用 laravel 5.5.1+ 添加带有任何捕获的最后一条路线不再适用