By 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 thejsonSerializemethod will be returned; - If the element implements the "Illuminate\Contracts\Support\Jsonable", the results of the
toJsonmethod will be returned; - If the element implements the "Illuminate\Contracts\Support\Arrayable", the results of the
toArraymethod 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'
∎