How to return laravel collection in json format - toJson() Method - Laravel Collection

  • 05-07-2022
  • 1557
  • Laravel 9
  • Haresh Chauhan

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-image

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-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :