Eloquent: 序列化
簡介
當構(gòu)建 JSON APIs 時猖任,你需要經(jīng)常的將你的模型和關聯(lián)轉(zhuǎn)換為數(shù)組或者 JSON 格式补履。Eloquent 包含了便捷的方法來進行這些轉(zhuǎn)換,以及控制哪些屬性應該包含在序列化之中太伊。
基礎用法
轉(zhuǎn)換模型到數(shù)組
為了將一個模型和其關聯(lián)加載的數(shù)據(jù)轉(zhuǎn)換為數(shù)組雇锡,你需要使用 toArray
方法。這個方法是一個遞歸的方法僚焦,所以所有的屬性和所有的關聯(lián)(包括關聯(lián)的關聯(lián))都會被轉(zhuǎn)換為數(shù)組:
$user = App\User::with('roles')->first();
return $user->toArray();
你也可以將集合轉(zhuǎn)換為數(shù)組:
$users = App\User::all();
return $users->toArray();
轉(zhuǎn)換模型到 JSON
你可以使用 toJson
方法來將一個模型轉(zhuǎn)換為 JSON锰提。就像 toArray
方法,toJson
方法也是遞歸方法芳悲,所以所有的屬性和其關聯(lián)將會被轉(zhuǎn)換為 JSON:
$user = App\User::find(1);
return $user->toJson();
另外立肘,你可以轉(zhuǎn)換模型或者集合到一個字符串中,它將會自動的調(diào)用 toJson
方法:
$user = App\User::find(1);
return (string) $user;
由于模型和集合都會在轉(zhuǎn)換為字符串時被自動的轉(zhuǎn)換為 JSON名扛。所以你可以直接在應用的路由或者控制器中返回 Eloquent 對象:
Route::get('users', function () {
return App\User::all();
});
從 JSON 中隱藏屬性
有時候你可能會選擇限制一些屬性的展示谅年,比如,密碼肮韧,這些本應包含在模型中的數(shù)值或者 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'];
}
注意:當隱藏一些關聯(lián)時旺订,你應該使用關聯(lián)模型的名字,而不是動態(tài)屬性的名字超燃。
另外区拳,你也可以使用 visible
屬性來定義一個白名單屬性集來指明這些屬性應該被包含在模型的數(shù)組或者 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
方法將返回模型實例劳闹,這樣有利于鏈式調(diào)用:
return $user->makeVisible('attribute')->toArray();
同樣,如果你希望在給定的模型實例中設置通城⑺玻可見的屬性為不可見本涕,那么你可以使用 makeHidden
方法:
return $user->makeHidden('attribute')->toArray();
追加值到 JSON
偶爾,你可能需要在模型中添加一些數(shù)據(jù)庫中不存在的字段的屬性伙窃。那么菩颖,你需要先為這個值定義一個訪問器:
<?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';
}
}
當你創(chuàng)建完訪問器之后,將其屬性的名稱添加到模型的 appends
屬性中:
<?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
列表中加入屬性之后为障,它就會被加入到模型的數(shù)組和 JSON 形式中晦闰。在 appends
數(shù)組中的屬性也受到模型中的 visible
和 hidden
設置的約束。