PASSWORD RESET

Your destination for complete Tech news

How to convert a Laravel collection to JSON?

533 0
< 1 min read

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
]
*/

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.