To convert a Laravel collection to JSON, you can use the toJson
method. This method will return the collection as a JSON string.
Here’s an example:
$collection = collect([1, 2, 3, 4, 5]);
$json = $collection->toJson();
// $json is now '[1,2,3,4,5]'
You can also pass an options argument to the toJson
method to customize the encoding options:
$collection = collect([1, 2, 3, 4, 5]);
$json = $collection->toJson(JSON_PRETTY_PRINT);
// $json is now a pretty-printed JSON string:
/*
[
1,
2,
3,
4,
5
]
*/