How to Convert JSON to Array in Laravel?

Hello Friends,

In this guide, we are going to learn how to convert json to array in laravel. I explained simply about how to convert json into array in laravel. This post will give you a simple example of how to convert json object to array in laravel. If you have a question about laravel convert json to array then I will give a simple example with a solution.

You can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 versions.

There are several different ways to convert JSON data into an array in Laravel application. In this example, I will give you two ways to convert JSON data into an array. in the first example, we will use json_decode() and in the second example, we will use json() method of HTTP response. so, let’s see both examples one by one.

Example 1: Using json_decode()

app/Http/Controllers/DemoController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class DemoController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$jsonData = '[

{ "id": 1, "name": "Hardik", "email": "[email protected]"},

{ "id": 2, "name": "Vimal", "email": "[email protected]"},

{ "id": 3, "name": "Harshad", "email": "[email protected]"}

]';

$data = json_decode($jsonData, true);

dd($data);

}

}

Output:

Array

(

[0] => Array

(

[id] => 1

[name] => Hardik

[email] => [email protected]

)

[1] => Array

(

[id] => 2

[name] => Vimal

[email] => [email protected]

)

[2] => Array

(

[id] => 3

[name] => Harshad

[email] => [email protected]

)

)

Example 2: Using json() Method

app/Http/Controllers/DemoController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use IlluminateSupportFacadesHttp;

class DemoController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$response = Http::get('https://jsonplaceholder.typicode.com/posts/1');

$data = $response->json();

dd($data);

}

}

Output:

Array

(

[userId] => 1

[id] => 1

[title] => sunt aut facere repellat provident occaecati excepturi optio reprehenderit

[body] => quia et suscipit

suscipit recusandae consequuntur expedita et cum

reprehenderit molestiae ut ut quas totam

nostrum rerum est autem sunt rem eveniet architecto

)

I hope it can help you…

1 thought on “How to Convert JSON to Array in Laravel?”

Leave a Comment