fromJson() in laravel 12.8

Bookmark

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 a Collection 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 like depth and flags, which are typically passed to PHP's native json_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.