Laravel 12.26 quietly dropped two gems that can make your code cleaner and your long-running jobs safer: toPrettyJson()
and withHeartbeat()
. Let’s break down what they do, why they matter, and how you can use them in real-world scenarios.
🧼 toPrettyJson()
— Say Goodbye to JSON_PRETTY_PRINT
Before 12.26, if you wanted readable JSON output, you had to do this:
$collection = collect(['name' => 'Sadique', 'role' => 'Developer']);
echo $collection->toJson(JSON_PRETTY_PRINT);
Now? Just:
echo $collection->toPrettyJson();
✅ Where It Works:
- Collections
- Models
- JSON Resources
- Paginators
- Fluent instances
- Message Bags
🔥 Why It Matters:
- Cleaner syntax
- Easier debugging
- Better readability in logs and exports
This is a small DX win, but one that adds polish to your workflow—especially when you’re building APIs or exporting data.
🫀 withHeartbeat()
— Keep Your Locks Alive in Long Jobs
This one’s a game-changer for batch processing, report generation, or any long-running task where you need to hold a lock.
🧠 The Problem:
You acquire a lock for a job, but if the job takes longer than expected, the lock might expire mid-process—or worse, never release.
💡 The Solution:
withHeartbeat()
lets you run a callback at regular intervals while lazily enumerating a collection. Perfect for refreshing locks.
$lock = Cache::lock('generate-reports', CarbonInterval::minutes(5));
$lock->acquire();
Reports::where('status', 'pending')
->lazy()
->withHeartbeat(CarbonInterval::minutes(4), fn() => $lock->reacquire())
->each(fn($report) => $this->generateReport($report));
$lock->release();
🛠 Use Cases:
- Report generation
- Queue workers
- Data migrations
- Any task where concurrency control matters
🧵 Final Thoughts
These features may seem minor, but they reflect Laravel’s commitment to developer experience. toPrettyJson()
simplifies your output, and withHeartbeat()
adds resilience to your backend processes.
If you’re building SaaS tools or developer utilities (like your Laravel Audit Dashboard), these additions can help you write cleaner, safer code with less boilerplate.