在PHP 中, JsonSerializable接口是處理對象序列化為JSON 的重要工具。它允許對象自定義JSON 編碼的行為,特別是在使用json_encode()時非常方便。在Laravel 項目中,掌握如何正確實現JsonSerializable::jsonSerialize方法,不僅能提升數據傳輸的靈活性,還能使API 返回結構更符合業務需求。
本文將帶你深入理解JsonSerializable ,並通過一個Laravel 實戰案例,展示如何應用它來定制JSON 輸出。
JsonSerializable是PHP 5.4 版本引入的接口,聲明了一個方法:
public function jsonSerialize();
該方法返回的數據會被json_encode()用作序列化內容。通過實現這個接口,類可以完全控制被轉換成JSON 的數據結構。
Laravel 本身使用Eloquent ORM 處理模型數據,通常模型會自動轉換成JSON。但有些場景你可能想要:
自定義JSON 返回字段和格式;
過濾敏感信息(如密碼、令牌);
嵌套關聯數據時更靈活地調整結構;
簡化前端處理的複雜度。
這時, JsonSerializable就非常合適。
假設我們有一個User模型,包含字段:
id
name
password
created_at
updated_at
我們希望:
輸出時隱藏password ;
將created_at格式化為簡潔時間字符串;
添加一個計算屬性profile_url 。
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use JsonSerializable;
class User extends Model implements JsonSerializable
{
// 允許批量賦值字段(根據需要)
protected $fillable = ['name', 'email', 'password'];
// 需要隱藏的字段
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);
// 直接返回對象,Laravel 會調用 jsonSerialize 自動序列化
return response()->json($user);
}
}
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
Route::get('user/{id}', [UserController::class, 'show']);
訪問http://gitbox.net/user/1返回:
{
"id": 1,
"name": "張三",
"email": "[email protected]",
"created_at": "2025-05-25 10:30",
"profile_url": "http://gitbox.net/profile/1"
}
可以看到:
password字段被隱藏了;
created_at格式美化了;
新增了profile_url字段。
JsonSerializable接口讓你可以完全控制模型序列化為JSON 的行為;
在Laravel 中結合Eloquent 使用非常方便,兼容性好;
適用於API 輸出定制、敏感數據保護、格式統一等場景;
配合Laravel 的response()->json()方法,使用簡潔、直觀。
如果你需要對JSON 數據結構有更細粒度的掌控, JsonSerializable::jsonSerialize是不可或缺的利器。