How to create a Laravel Collection From JSON

Today i have to create a laravel collection from a JSON object. I search on the internet and I cant find the best solution anywhere.. I saw too many articles related to converting laravel collection into JSON .. after reading so many documents i found a way to Create a laravel collection from Json.

So here in this tutorial, I will share you

How to create a Laravel Collection from JSON [example 1]

//get json data

$getjson= Http::acceptJson()->get('enterJSON_API-url_here')->throw()->json();      

// Creating Laravel collection

$laravelcollection = collect($getjson)->values();

 

So you can use this laravel collection like any other model.



How to create a Laravel Collection from JSON [example 2]

// get json using curl
$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => "Enter API URL HERE",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",    
]);

$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);  
          
// decode json 
$response = json_decode($response, true);

//create laravel collection
$collection =  collect($response);

 

Hope this Helps ..

Checkout more awesome laravel tutorials 

Post Your Questions on our forum

Post a question on Forum

Ajith Jojo Joseph

Self taught, dedicated young entrepreneur with many licensed products under his sleeve. Passionate about technology, business and excellence in general.

Share with your friends:

Comments are closed.

How to get data from a model on all pages in Laravel – Simple Way

Do you know How to get data from a model on all pages in Laravel ? In this blog post, […]

August 5, 2022

How to create a Laravel Collection From JSON

Today i have to create a laravel collection from a JSON object. I search on the internet and I cant […]

August 3, 2022

Laravel Eloquent WhereNull() and whereNotNull() Example

Do you know how to use WhereNull() and whereNotNull() Laravel Eloquent. In this post, I will explain how to use […]

July 28, 2022

Laravel Array to JSON Response From Laravel Controller

Do you know how to make JSON responses from a Laravel array? As a developer someday we all have to […]

July 28, 2022

Digital Marketing Toolkit

Get Free Access to Digital Marketing Toolkit. You can use all our tools without any limits

Get Free Access Now