Search

Laravel 5 Collections: Converting a Collection to JSON With PHP's Magic __toString Method

April 22, 2018 —John Koster

When a Collection instance is cast into a string, its JSON representation is returned as the result. Internally this is accomplished by returning the results of the collection's toJson method.

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 'name' => 'Flo'
6]);
7 
8// Cast the collection to a string.
9$stringValue = (string) $collection;

After the above code has executed, the $stringValue variable will contain the following value:

1{"name":"Flo"}

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.