How to Convert JSON to Collection in Laravel?

By Hardik Savani February 1, 2024 Category : Laravel

In this post, i will show you how to convert json to collection in laravel. i will give you very simple controller code for laravel convert json to collection.

In this example, i will create simple controller method and take json variable. Then i will convert json to collection using "collect()" and json_decode() method. so, let's see the simple example with output code:

Example:

You can see the following controller code:

app/Http/Controllers/HomeController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller

{

/**

* Create a new controller instance.

*

* @return void

*/

public function index()

{

/* Your JSON string */

$jsonString = '{

"name": "Hardik Savani",

"age": 30,

"city": "Rajkot"

}';

/* Convert JSON string to a collection */

$dataCollection = collect(json_decode($jsonString, true));

dd($dataCollection);

}

}

Output:

Illuminate\Support\Collection {#1881 â–¼

#items: array:3 [â–¼

"name" => "Hardik Savani"

"age" => 30

"city" => "Rajkot"

]

}

I hope it can help you...

Shares