Mastering Laravel 12.26: Pretty JSON and Heartbeat Collections
Overview
toPrettyJson method simplifies data visualization, while withHeartbeat brings a native way to manage background maintenance within
Prerequisites
To get the most out of this tutorial, you should have a solid grasp of
Key Libraries & Tools
- Laravel 12.26: The core framework providing these new methods.
- Carbon: Used for defining the time intervals for the heartbeat feature.
- LazyCollection: The specific collection class that supports the new periodic callback functionality.
Code Walkthrough
Readable JSON Outputs
The toPrettyJson method is a quality-of-life improvement. Instead of manually passing the JSON_PRETTY_PRINT flag to a native function, you can now chain this directly onto your data objects.
// Traditional way
return json_encode($user, JSON_PRETTY_PRINT);
// Laravel 12.26 way
return $user->toPrettyJson();
Implementing the Heartbeat
The withHeartbeat method allows a
use Illuminate\Support\CarbonInterval;
use Illuminate\Support\Facades\File;
File::lines('large_data.csv')
->withHeartbeat(CarbonInterval::seconds(5), function () {
// This runs every 5 seconds of processing time
dump('Heartbeat: Still processing...');
})
->each(function ($line) {
// Process each line
});
Syntax Notes
The withHeartbeat method requires two arguments: a CarbonInterval or a duration in seconds, and a closure. Under the hood,
Practical Examples
A primary use case involves processing large CSV imports that require a withHeartbeat to refresh that lock every 45 seconds. This ensures the lock remains active exactly as long as the process runs, then expires naturally if the script crashes.
Tips & Gotchas
Remember that the heartbeat only triggers during active iteration. If your collection logic includes a heavy sleep() or a blocking network call outside the iterator, the heartbeat will wait until the current item finishes processing to check the time. Always use withHeartbeat with efficient logging to monitor background job health.
