Member-only story
Mastering JSON Serialization in Laravel for API Responses
2 min readJan 21, 2025
Laravel simplifies the process of transforming Eloquent models into JSON, a crucial step for building robust API responses. Among its many tools, the toJson()
method stands out for its straightforward implementation and flexibility. With just a single call, you can serialize your models and tailor the output to suit your application's needs.
Basic Usage of toJson()
Here’s a simple example of using toJson()
to convert a model into a JSON response:
$user = User::find(1);
return $user->toJson();
For enhanced readability or debugging, you can enable JSON formatting options like JSON_PRETTY_PRINT
:
return $user->toJson(JSON_PRETTY_PRINT);
Practical Example: Building a Custom API Response
Let’s dive into a more advanced example that demonstrates how to customize JSON serialization for an API.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
// Add custom attributes
protected $appends = ['reading_time'];
// Hide sensitive or unnecessary attributes
protected $hidden = ['internal_notes'];
public function author()
{
return…