# Eloquent: 序列化
- [簡介](#introduction)
- [序列化模型 & 集合](#serializing-models-and-collections)
- [序列化成數組](#serializing-to-arrays)
- [序列化成 JSON](#serializing-to-json)
- [隱藏來自 JSON 的屬性](#hiding-attributes-from-json)
- [添加參數到 JSON 中](#appending-values-to-json)
<a name="introduction"></a>
## 簡介
當你在創建 JSON API 的時候,經常會需要將模型和關聯轉換成數組或 JSON。Eloquent 提供了一些便捷的方法來讓我們可以完成這些轉換,以及控制哪些屬性需要被包括在序列化中。
<a name="serializing-models-and-collections"></a>
## 序列化模型 & 集合
<a name="serializing-to-arrays"></a>
### 序列化成數組
如果要將模型還有其加載的[關聯](/docs/{{version}}/eloquent-relationships)轉換成一個數組,則可以使用 toArray 方法。這個方法是遞歸的,因此,所有屬性和關聯(包含關聯中的關聯)都會被轉換成數組:
$user = App\User::with('roles')->first();
return $user->toArray();
你也可以將整個[集合](/docs/{{version}}/eloquent-collections)轉換成數組:
$users = App\User::all();
return $users->toArray();
<a name="serializing-to-json"></a>
### 序列化成 JSON
如果要將模型轉換成 JSON,則可以使用 `toJson` 方法。如同 `toArray`方法一樣, `toJson` 方法也是遞歸的。因此,所有的屬性以及關聯都會被轉換成 JSON:
$user = App\User::find(1);
return $user->toJson();
或者,你也可以強制把一個模型或集合轉型成一個字符串,它將會自動調用 `toJson` 方法:
$user = App\User::find(1);
return (string) $user;
當模型或集合被轉型成字符串時,模型或集合便會被轉換成 JSON 格式,因此你可以直接從應用程序的路由或者控制器中返回 Eloquent 對象:
Route::get('users', function () {
return App\User::all();
});
<a name="hiding-attributes-from-json"></a>
## 隱藏來自 JSON 的屬性
有時候你可能會想要限制包含在模型數組或 JSON 表示中的屬性,比如說密碼。則可以通過在模型中增加 `$hidden` 屬性定義來實現:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = ['password'];
}
> {note} 當你要對關聯進行隱藏時,需使用關聯的 方法 名稱,而不是它的動態屬性名稱。
另外,你也可以使用 `visible` 屬性來定義應該包含在你的模型數組和 JSON 表示中的屬性白名單。白名單外的其他屬性將隱藏,不會出現在轉換后的數組或 JSON 中:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The attributes that should be visible in arrays.
*
* @var array
*/
protected $visible = ['first_name', 'last_name'];
}
#### 臨時修改屬性的可見度
你可以在模型實例后使用 `makeVisible` 方法來顯示通常隱藏的屬性,且為了便于使用, `makeVisible` 方法會返回一個模型實例:
return $user->makeVisible('attribute')->toArray();
相應的,你可以在模型實例后使用 `makeHidden` 方法來隱藏通常顯示的屬性:
return $user->makeHidden('attribute')->toArray();
<a name="appending-values-to-json"></a>
## 添加參數到 JSON 中
有時候,在轉換模型到 數組 或 JSON 時,你希望添加一個在數據庫中沒有對應字段的屬性。首先你需要為這個值定義一個 [訪問器](/docs/{{version}}/eloquent-mutators):
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the administrator flag for the user.
*
* @return bool
*/
public function getIsAdminAttribute()
{
return $this->attributes['admin'] == 'yes';
}
}
訪問器創建成功后,只需添加該屬性到改模型的 `appends` 屬性中。注意,屬性名稱通常遵循 「Snake Case」, 的命名方式,即是訪問器的名稱是基于 「Camel Case」 的命名方式。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = ['is_admin'];
}
一旦屬性被添加到 `appends` 清單,便會將模型中的數組和 JSON 這兩種形式都包含進去。在 `appends` 數組中的屬性也遵循模型中 `visible` 和 `hidden` 設置。
## 譯者署名
| 用戶名 | 頭像 | 職能 | 簽名 |
| ---------------------------------------- | ---------------------------------------- | ---- | ---------------------------------------- |
| [@GanymedeNil](https://github.com/GanymedeNil) | <img class="avatar-66 rm-style" src="https://dn-phphub.qbox.me/uploads/avatars/6859_1487055454.jpg?imageView2/1/w/100/h/100"> | 翻譯 | 爭做一個 Full Stack Developer [@GanymedeNil](http://weibo.com/jinhongyang) |
---
> {note} 歡迎任何形式的轉載,但請務必注明出處,尊重他人勞動共創開源社區。
>
> 轉載請注明:本文檔由 Laravel China 社區 [laravel-china.org](https://laravel-china.org) 組織翻譯,詳見 [翻譯召集帖](https://laravel-china.org/topics/5756/laravel-55-document-translation-call-come-and-join-the-translation)。
>
> 文檔永久地址: https://d.laravel-china.org
- 說明
- 翻譯說明
- 發行說明
- 升級說明
- 貢獻導引
- 入門指南
- 安裝
- 配置信息
- 文件夾結構
- HomeStead
- Valet
- 核心架構
- 請求周期
- 服務容器
- 服務提供者
- 門面(Facades)
- Contracts
- 基礎功能
- 路由
- 中間件
- CSRF 保護
- 控制器
- 請求
- 響應
- 視圖
- 重定向
- Session
- 表單驗證
- 錯誤與日志
- 前端開發
- Blade 模板
- 本地化
- 前端指南
- 編輯資源 Mix
- 安全
- 用戶認證
- API認證
- 用戶授權
- 加密解密
- 哈希
- 重置密碼
- 綜合話題
- Artisan 命令行
- 廣播系統
- 緩存系統
- 集合
- 事件系統
- 文件存儲
- 輔助函數
- 郵件發送
- 消息通知
- 擴展包開發
- 隊列
- 任務調度
- 數據庫
- 快速入門
- 查詢構造器
- 分頁
- 數據庫遷移
- 數據填充
- Redis
- Eloquent ORM
- 快速入門
- 模型關聯
- Eloquent 集合
- 修改器
- API 資源
- 序列化
- 測試
- 快速入門
- HTTP 測試
- 瀏覽器測試 Dusk
- 數據庫測試
- 測試模擬器
- 官方擴展包
- Cashier 交易工具包
- Envoy 部署工具
- Horizon
- Passport OAuth 認證
- Scout 全文搜索
- Socialite 社交化登錄
- 交流說明