How to Convert JSON to Collection in Laravel

AuthorSumit Dey Sarkar

Pubish Date04 Feb 2024


In this tutorial, we will learn how to convert JSON to Collection in Laravel.

How to Convert JSON to Collection in Laravel

Convert JSON to Collection in Laravel

Assuming you have the following JSON string:

    "name": "John",
    "age": 30,
    "city": "New York"

You can convert it to a Laravel Collection and output the values like this:

use Illuminate\Support\Collection;

$jsonString = '{"name": "John", "age": 30, "city": "New York"}';

// Convert JSON to Collection
$collection = collect(json_decode($jsonString, true));

// Access data from the collection
$name = $collection->get('name');
$age = $collection->get('age');
$city = $collection->get('city');

// Output the values
echo "Name: $name, Age: $age, City: $city";

Output :

Name: John, Age: 30, City: New York

In the above example

  • json_decode($jsonString, true) is used to decode the JSON string into an associative array.
  • collect() is used to convert the associative array into a Laravel Collection.
  • The get method of the Collection is used to retrieve values by their keys.
Comments 0

Leave a comment