Laravel 5 Collections: Converting a Collection Into Something JSON Serializable With jsonSerialize

April 22, 2018 —John Koster

The jsonSerialize method will convert the contents of the collection into something that be serialized using PHP's json_encode function. This method will iterate the collection's internal array and will evaluate each element in accordance with the following rules:

  • If the element implements the JsonSerializable, the results of the jsonSerialize method will be returned;
  • If the element implements the "Illuminate\Contracts\Support\Jsonable", the results of the toJson method will be returned;
  • If the element implements the "Illuminate\Contracts\Support\Arrayable", the results of the toArray method will be returned;
  • If none of the previous rules are satisfied, the element will be returned unaltered.

#Signature

1public function jsonSerialize();

#Example Use

The following code example demonstrates the basic use of the jsonSerialize method:

1use Illuminate\Support\Collection;
2 
3// Create a new collection.
4$collection = new Collection([
5 'first', 'second', 'third'
6]);
7 
8// Get the value that should be encoded with
9// json_encode.
10$value = $collection->jsonSerialize();

The $value variable would contain a value similar to the following output:

1array
2 0 => string 'first'
3 1 => string 'second'
4 2 => string 'third'

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.