[英]How to check if current url is valid in Laravel?
What I want to do我想做的事
laravel/routes/web.php laravel/routes/web.php
Route::get('sample', 'SampleController@index');
In this case, http://localhost:8000/sample is valid.在这种情况下,http://localhost:8000/sample 是有效的。
But http://localhost:8000/test is not valid because it's not defined.但是 http://localhost:8000/test 无效,因为它没有定义。
Current Code当前代码
return \Route::current() ? true : false;
It doesn't return null:它不返回 null:
\Route::current()
returns \Illuminate\Routing\Route
. \Route::current()
返回\Illuminate\Routing\Route
。
function isRoutePresent($urlToCheck)
{
$available_url = [];
$routes = Route::getRoutes();
foreach ($routes as $route) {
array_push($available_url, url($route->uri));
}
return in_array($urlToCheck, $available_url);
}
You can then call isRoutePresent("http://localhost:8000/test")
to return true
or false
然后您可以调用
isRoutePresent("http://localhost:8000/test")
来返回true
或false
If you want to test if a URI will match a registered route you can call match
on the Route Collection:如果你想测试一个 URI 是否匹配一个注册的路由,你可以在路由集合上调用
match
:
$request = \Illuminate\Http\Request::create('admin', 'get');
try {
$match = Route::getRoutes()->match($request);
} catch (\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e) {
// no match
}
Though, not entirely sure what your intentions are.虽然,不完全确定你的意图是什么。
Testing if the current route itself is valid doesn't make sense because for their to be a current route means it matched a route and it is valid.测试当前路由本身是否有效是没有意义的,因为它们成为当前路由意味着它匹配了一个路由并且它是有效的。 If a request was not valid then there would be a 404 returned or bad method exception.
如果请求无效,则将返回 404 或错误方法异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.