$routes = Route::getRoutes();
$request = Request::create('the/url/you/want/to/check');
try {
$routes->match($request);
// route exists
}
catch (\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e){
// route doesn't exist
}
NotFoundHttpException
。相反,我得到了一个带有uri的路由对象:{fallbackPlaceholder}
。有什么想法吗? - Themba Clarence Malunganiprotected function routeExists(string $url): bool
{
$routes = Route::getRoutes();
$request = Request::create($url);
return (bool) $routes->match($request)->getName();
}
$this->routeExists($this->request->fullUrl())
- Kal既然您提到要检查外部URL(例如:https://google.com
),而不是应用程序内的路由,则可以使用Laravel中的Http
门面,如下所示(https://laravel.com/docs/master/http-client):
use Illuminate\Support\Facades\Http;
$response = Http::get('https://google.com');
if( $response->successful() ) {
// Do something ...
}
虽然没有特定的 Laravel 函数,但你可以尝试一下这个。
function urlExists($url = NULL)
{
if ($url == NULL) return false;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ($httpcode >= 200 && $httpcode < 300) ? true : false;
}
试试这个函数
function checkRoute($route) {
$routes = \Route::getRoutes()->getRoutes();
foreach($routes as $r){
if($r->getUri() == $route){
return true;
}
}
return false;
}
$routes->match()
可以解决这个问题。 - 2519211