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
How can I check whether the route "URL" exists?
提问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 /welcome
or /test
it should route them to the correct controller. If you where to hit /hello
it should go to the MainController
and hit function getPage($page)
with $page
being the page you hit.
如果您要击中/welcome
或/test
应该将它们路由到正确的控制器。如果你在哪里打/hello
它应该去MainController
和命中功能getPage($page)
与$page
被你打的页面。
If it hits MainController@getPage
you 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.php
from resources/views/errors
.
如果你不知道的是,abort(404)
将返回视图404.blade.php
的resources/views/errors
。
回答by TGA
Adding last route with any catch doesn't works anymore with laravel 5.5.1+
使用 laravel 5.5.1+ 添加带有任何捕获的最后一条路线不再适用