简体   繁体   中英

What's Laravel best way to build an external URL with query string?

I'm currently building a project with Laravel and I need to build URLs with query strings. URL:: functions and url(), action(), etc. are out of the question since they mainly built for internal use. The urls I need to create are external.

A similar example I could give is an external URL for the static images Google Maps api :

https://maps.googleapis.com/maps/api/staticmap?center=New+York,NY&zoom=13&size=600x300&key=KEY

If you have the array :

<!-- language: lang-php -->
array(
    'center'=>'New York, NY',
    'zoom'=>13,
    'size'=>'600x300'
)

I'm mainly asking that because it's currently impossible for me to install http_build_url / query extension and because there are many functions that do this internally. I just can't find the best place to "plug" myself.

If you need to reinvent the wheel (which sucks, sorry to hear), you could do something like this.

$queryString = '';
$arrayLength = count($myArray);
foreach ($myArray as $key => $val) {
    $queryString .= urlencode($key) . '=' . urlencode($val);
    $arrayLength--;
    if ($arrayLength) {
        $queryString .= '&';
    }
}

I'd save it as a function, and have a separate function for constructing the url, eg

function buildUrl($baseUri, $params) {
    return sprintf("%s?%s", $baseUri, buildQueryString($params));
}

But I'm not 100 % that this is what you really want, so apologies if I'm wrong.

Edit: Four years later, given that they asked for Laravel methods, I would do something like this:

collect($array)->map(function ($value, $key) {
    return urlencode($key) . '=' . urlencode($value);
})->join('&');

Simple string concatenating:

$myStr = 'puppies.';
echo 'Dogs have '.$myStr;

Output:

Dogs have puppies.

You can just concatenate the elements of the array with the url string in the same manner:

$values = Array(
                'center'=>'New York, NY',
                'zoom'=>13,
                'size'=>'600x300'
                 )

$urlTemp = 'https://maps.googleapis.com/maps/api/staticmapcenter=';

$url     =  $urlTemp.$values['center']
           .'&zoom='.$values['zoom']
           .'&size='.$values['size']
           .'&key=KEY';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM