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 

Ajith Jojo Joseph

Hire Me for Freelancing $30/Hour ,
Contact via email : [email protected]

Share with your friends:

Comments are closed.

How To Generate A PDF from HTML in Laravel 11

Hello , I was trying to generate a PDF payment receipt for my SAAS application and when i search for […]

June 22, 2024

How to create Laravel Flash Messages

Laravel flash messages are a convenient way to display one-time notifications to the user after a form submission or other […]

December 22, 2022

How to make Custom Artisan Command in Laravel

Custom Artisan commands are a useful feature of Laravel that allow you to define your own command-line commands for tasks […]

December 22, 2022

Tips for Laravel migrations

Laravel migrations are a powerful tool for managing and modifying your database schema in a structured and organized way. Here […]

December 22, 2022

Digital Marketing Toolkit

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

Get Free Access Now