fromJson() in laravel 12.8
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 aCollection
instance:
$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 likedepth
andflags
, 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 intuitive^1_2.