In Laravel 12.8, the fromJson() method was introduced as part of the Collection class. This method simplifies the process of creating a collection from a JSON string. Here’s how it works:
Usage
- Before Laravel 12.8:
You would create a collection from JSON using
json_decode()followed by manually wrapping it in aCollectioninstance:
$collection = new Collection(json_decode($json, true));
- After Laravel 12.8:
You can directly use the
fromJson()method:
$collection = Collection::fromJson($json);
Features
- The
fromJson()method supports additional arguments likedepthandflags, which are typically passed to PHP’s nativejson_decode()function:
$collection = Collection::fromJson(json: $json, flags: JSON_THROW_ON_ERROR);
This enhancement streamlines JSON parsing for collections, making code cleaner and more intuitive12.