构建 JSON API 时,你经常需要将你的模型和关系转换为数组或 JSON。模型包含便捷方法,用于进行这些转换,以及控制哪些属性包含在你的序列化中。
要将模型及其已加载的 关系 转换为数组,可以使用 toArray 方法。此方法是递归的,因此所有属性和所有关系(包括关系的子关系)都将转换为数组:
$user = User::with('roles')->first();
return $user->toArray();您也可以将 集合 转换为数组:
$users = User::all();
return $users->toArray();要将模型转换为 JSON,您可以使用 toJson 方法。与 toArray 类似,toJson 方法是递归的,因此所有属性和关联都将转换为 JSON:
$user = User::find(1);
return $user->toJson();或者,您可以将模型或集合转换为字符串,这会自动调用 toJson 方法:
$user = User::find(1);
return (string) $user;由于模型和集合在转换为字符串时会转换为 JSON,你可以直接从你的应用程序的路由、AJAX 处理器或控制器中返回模型对象:
Route::get('users', function () {
return User::all();
});有时您可能希望限制包含在模型的数组或 JSON 表示中的属性,例如密码。为此,请在模型中添加 $hidden 属性定义:
namespace Acme\Blog\Models;
use Model;
class User extends Model
{
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = ['password'];
}或者,你可以使用 $visible 属性来定义一个属性白名单,这些属性应该包含在你的模型的数组和 JSON 表示中:
class User extends Model
{
/**
* The attributes that should be visible in arrays.
*
* @var array
*/
protected $visible = ['first_name', 'last_name'];
}偶尔,你可能需要添加在数据库中没有对应列的数组属性。为此,首先定义一个访问器用于该值:
class User extends Model
{
/**
* Get the administrator flag for the user.
*
* @return bool
*/
public function getIsAdminAttribute()
{
return $this->attributes['admin'] == 'yes';
}
}一旦你创建了访问器,将属性名添加到模型的 appends 属性中:
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 设置。