Streamlining Eloquent: JSON Collections, Mass Assignment, and Automatic Eager Loading
Overview of Laravel 12.8 Enhancements
Direct Collection Creation from JSON
Historically, converting a JSON string into a fromJson() method simplifies this into a single call. This is particularly useful when handling API responses or configuration stored in database text fields.
// Old Way
$data = json_decode($jsonString, true);
$collection = collect($data);
// New Laravel 12.8 Way
$collection = Collection::fromJson($jsonString);
Bypassing Mass Assignment with forceCreateMany
When importing data, you might encounter models where specific fields aren't in the $fillable array for security reasons. Previously, if you wanted to bulk-insert these via a relationship, you had to loop and call forceCreate() individually. forceCreateMany() to handle this efficiently.
$post->comments()->forceCreateMany([
['content' => 'First comment', 'user_id' => 1],
['content' => 'Second comment', 'user_id' => 2],
]);
You can also use forceCreateManyQuietly() to prevent model events from firing during the creation process.
Solving N+1 with Automatic Eager Loading
The most significant update is the introduction of automatic relation loading. This feature detects when a relationship is being accessed in a loop and automatically eager loads it to prevent excessive database queries. You can enable this globally in your AppServiceProvider or on a specific collection.
// Global enablement
Model::automaticallyEagerLoadRelationships();
// Dynamic enablement on a specific result set
$users = User::all()->withRelationshipAutoloading();
Tips & Gotchas
- Conventions Matter: Automatic eager loading relies on standard Laravelnaming conventions. If your relationships use custom foreign keys that deviate from the standard, the automation might fail.
- JSON Integrity: Ensure your JSON is valid before using
fromJson(), as it still relies on successful decoding under the hood. - Force Create Risks: Only use
forceCreateMany()when you trust the source data, as it ignores all mass-assignment protections.
