Laravel is there a way to detect if a given url have the same host as my project host?

76 Views Asked by At

Basically I'm writing a snippet that checks whether or not a given link have the same host as my server host. For example a given link is https://example.test/another_link and my host is not_example.test. So basically if it is the same then I'll redirect to that normally but if not then I'd have to redirect to my home page (https://not_example.test/home).

I tried hardcoding it but issue is some of my co-workers have different host names like not_example1.test so basically I hate to ask them to change it every time. Obviously Route::has only works if it have a named route and if our route list expands it's gonna be a pain to add every named route.

2

There are 2 best solutions below

0
hassan On BEST ANSWER

You can use request()->getHttpHost() to compare it with a given URL from input, and you can get the host of a given URL by a multiple ways, the easiest way is to get is using parse_url

$inputUrl = parse_url(request()->get('some_input'),  PHP_URL_HOST);
if (request()->getHttpHost() == $inputUrl) {
   // do something
}
0
afcyy On

You can also use Spatie/Url to check both hosts and compare to each other

<?php

use Spatie\Url\Url;

$requestHost = Url::fromString(request()->url())->getHost();
$appHost = Url::fromString(config('app.url'))->getHost();

if ($requestHost === $appHost) {
    return redirect();
} 

return redirect();