What Is Laravel Collections?
Laravel collections are one of the most powerful tools and smart collection of the data of the laravel application. Simple we can say collections are PHP arrays but it's object-oriented in the laravel framework with deals with PHP array.
That all collections are base on PHP array but the most advantage of it is can be used object oriented.
toJson()
The Laravel collection is easy way to interface with the PHP array, So today we will discuss about toJson() laravel collection method. It will convert laravel collection in to JSON format.
This toJson() method will return JSON ENCODED data from the laravel collection, We already use json_encode in PHP array.
Signature
The signature of toJson() the method in the laravel collection is something like the below code in the laravel application.
/**
* Get the collection of items as JSON.
*
* @param int $options
* @return string
*/
public function toJson($options = 0)
{
return json_encode($this->jsonSerialize(), $options);
}
Example
This is how toJson() can be used in the laravel eloquent model.
use App\Models\User; $user = User::find($id)->toJson(); dd($user);
This is how toJson() the method can be used to laravel collection.
return collect(['name' => 'haresh','age' => 33])->toJson();
To print the formatted value, we can also pass the JSON_PRETTY_PRINT content as an option inside the toJson() method as an argument.
This will give you prettyprint format of the JSON.
return collect(['name' => 'haresh','age' => 33])->toJson(JSON_PRETTY_PRINT);
This is how to can return a response in JSON format for the laravel controller. form the HTTP request-response.
return \Response::json([
'data' => 'array of data'
], 200);
We always thanks to you for reading our blogs.
Dharmesh Chauhan
(Swapinfoway Founder)Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us
Haresh Chauhan
(Co-Founder)We Are Also Recommending You :
- How To Get Youtube Video Thumbnail From URL In PHP - Laravel
- How To Get Current Request Method Post Patch Get In Laravel - PHP
- Laravel 6 - Preview and Crop Image Before Upload using Ajax
- How To Add Active Class To Menu Item In Laravel
- File name required when file upload laravel validation rules
- Laravel Remove index.php From URL
- Laravel-9 Multi Authentication Guard Passport API Example
- HTTP Client Guzzle Package With Basic Usage In Laravel
- Arr::add() | Laravel Helper Function
- Median() Method | How It is Different From avg() Method In Laravel Collection