In PHP, the JsonSerializable interface is an important tool for handling object serialization to JSON. It allows objects to customize the behavior of JSON encoding, especially when using json_encode() . In the Laravel project, mastering how to correctly implement the JsonSerializable::jsonSerialize method can not only improve the flexibility of data transmission, but also make the API return structure more in line with business needs.
This article will take you to understand JsonSerializable in depth and use a Laravel practical case to show how to apply it to customize JSON output.
JsonSerializable is an interface introduced in PHP 5.4 version, declaring a method:
public function jsonSerialize();
The data returned by this method will be used as serialized by json_encode() . By implementing this interface, the class can fully control the data structure converted to JSON.
Laravel itself uses Eloquent ORM to process model data, and the model is usually automatically converted to JSON. But there are some scenarios you might want:
Custom JSON returns fields and formats;
Filter sensitive information (such as passwords, tokens);
More flexible adjustment of structure when nesting associated data;
Simplify the complexity of front-end processing.
At this time, JsonSerializable is very suitable.
Suppose we have a User model with fields:
id
name
password
created_at
updated_at
We hope:
Hide password when output;
Format created_at as a concise time string;
Add a computed property profile_url .
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use JsonSerializable;
class User extends Model implements JsonSerializable
{
// Allow batch assignment fields(As needed)
protected $fillable = ['name', 'email', 'password'];
// Fields that need to be hidden
protected $hidden = ['password'];
public function jsonSerialize()
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'created_at' => $this->created_at->format('Y-m-d H:i'),
'profile_url' => url('gitbox.net/profile/' . $this->id),
];
}
}
<?php
namespace App\Http\Controllers;
use App\Models\User;
class UserController extends Controller
{
public function show($id)
{
$user = User::findOrFail($id);
// Return to the object directly,Laravel Will call jsonSerialize Automatic serialization
return response()->json($user);
}
}
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
Route::get('user/{id}', [UserController::class, 'show']);
Visit http://gitbox.net/user/1 to return:
{
"id": 1,
"name": "Zhang San",
"email": "[email protected]",
"created_at": "2025-05-25 10:30",
"profile_url": "http://gitbox.net/profile/1"
}
You can see:
The password field is hidden;
created_at format beautified;
Added profile_url field.
The JsonSerializable interface allows you to fully control the behavior of model serialization to JSON;
It is very convenient to use in combination with Eloquent in Laravel and has good compatibility;
Suitable for API output customization, sensitive data protection, format uniformity and other scenarios;
In conjunction with Laravel's response()->json() method, it is concise and intuitive.
If you need to have a finer granular control over JSON data structures, JsonSerializable::jsonSerialize is an indispensable tool.