How to build query string from an array using Laravel helper

Laravel provide a helper Arr::query() to build query string from an array, an alternative to core php http_build_query() method.

Tested with Laravel versions 5.8, 6 and 7.

Kindly check for your version on official helpers page.

You need to import Illuminate\Support\Arr namespace with use keyword.

Example 1

use Illuminate\Support\Arr;

$data = [
    'search' => 'birds',
    'sourceType' => 'image',
];

echo Arr::query($data);

/*
 * Output
 *
 * "search=birds&sourceType=image"
*/

Example 2

use Illuminate\Support\Arr;

$data = [
    'firstName' => 'Jack',
    'lastName' => 'Doe',
    'socialAccount' => [
      'instagram' => 'meshworld.india',
      'facebook' => 'meshworldindia',
      'twitter' => 'meshworldindia',
    ],
];

echo Arr::query($data);

/*
 * Output
 *
 * "firstName=Jack&lastName=Doe&socialAccount%5Binstagram%5D=meshworld.india&socialAccount%5Bfacebook%5D=meshworldindia&socialAccount%5Btwitter%5D=meshworldindia"
*/

Laravel provides many useful helpers worth checking.

Happy coding

Vishnu Damwala
Vishnu Damwala

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳