如何通过Laravel检查URL是否存在?

6

2
你想要检查一个 Laravel 内部路由还是外部 URL? - DouglasDC3
@DouglasDC3:我不知道有什么区别。我想检查一个外部网址。 - Howard
最佳方式已在你添加的另一篇帖子中描述。 - DouglasDC3
@DouglasDC3:你的意思是说没有办法通过Laravel来实现这个吗? - Howard
据我所知,没有。我已经调查过了,Laravel不提供这种功能。 - DouglasDC3
4个回答

9
我假设您想要检查是否存在匹配特定URL的路由。
$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
}

1
有没有一种方法可以通过Laravel检查外部URL? - Howard
OP提到他想要检查一个外部URL,他没有说应用程序内的路由。 - Max S.
1
出现了某些问题,即使路由不存在,我也没有收到NotFoundHttpException。相反,我得到了一个带有uri的路由对象:{fallbackPlaceholder}。有什么想法吗? - Themba Clarence Malungani
@ThembaClarenceMalungani 像这样:protected function routeExists(string $url): bool { $routes = Route::getRoutes(); $request = Request::create($url); return (bool) $routes->match($request)->getName(); } $this->routeExists($this->request->fullUrl()) - Kal

3

既然您提到要检查外部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 ...
}

2

虽然没有特定的 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;        
   }

0

试试这个函数

function checkRoute($route) {
    $routes = \Route::getRoutes()->getRoutes();
    foreach($routes as $r){
        if($r->getUri() == $route){
            return true;
        }
    }

    return false;
}

1
这对于路由参数无效 - 使用$routes->match()可以解决这个问题。 - 2519211

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接