Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructing an external URL within Laravel

Tags:

url

php

laravel

Laravel has some excellent routing handling classes / methods. One of them is the Illuminate\Routing\UrlGenerator class, which is able to handle all sorts of complex URL generation relating to routing within your application.

I've been unable to find any sort of helper methods to construct an external URL string, similar to how UrlGenerator's to() method works (taking in a path, and any extra query parameters.) An example of an external URL would be a URL with a base host, and some sort of extra parameters, like this: https://www.youtube.com/watch?v=mDotS5BDqRM

Is there anything in Laravel that could help me construct an external URL similar to the to() method? I am not asking how to manually concatenate a string to create a URL, nor directly calling the format() method in UrlGenerator.

Thanks!

like image 677
1000Nettles Avatar asked Dec 30 '25 09:12

1000Nettles


1 Answers

Laravel provides URL building for your application's controllers because it knows about your routes and how those are constructed in order for Laravel to work.

Laravel does not provide generic URL building, because it errs on the side of KISS: not all applications need to build external URL. Some applications don't require external links. Some require only static links. Others, seemingly like yours, need to build URI in application-specific ways.

You might use an external package like spatie/url, or phpleague/uri (which can handle IRI well), or any of the others -- whether they are PSR-7 compliant or not. You can also roll your own, along the lines of:

function build_external_url(string $host, string $path = null, array $query = [], string $schema = null, int $port = null): string
{                                                                                
    $url = $host;                                                                
    if (null !== $port) {                                                     
        $url .= ':' . $port;                                                  
    }                                                                         
    if (null !== $path) {                                                        
        $url .= '/' . ltrim($path, '/');                                      
    }                                                                         
    if (! empty($query)) {                                                    
        $url .= '?' . http_build_query($query);                               
    }                                                                         
    return (null === $schema ? $url : ($schema . '://' . $url));               
}

See it live on 3v4l.org.

like image 137
bishop Avatar answered Dec 31 '25 22:12

bishop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!