教程 > Laravel 5.8

序列化

序列化

序列化


Eloquent: 序列化

  • 简介
  • 序列化模型 & 集合
    • 序列化为数组
    • 序列化为 JSON
  • 隐藏 JSON 属性
  • 追加 JSON 值
  • 序列化日期

简介

构建 JSON API 时,经常需要把模型和关联转化为数组或 JSON。针对这些操作,Eloquent 提供了一些便捷方法,以及对序列化中的属性控制。

序列化模型 & 集合

序列化为数组

要转化模型及其加载的 关联 为数组,可以使用 toArray 方法。这是一个递归的方法,因此所有的属性和关联(包括关联的关联)都将转化成数组:

$user = App\User::with('roles')->first();return $user->toArray();

也可以转化整个模型 集合 为数组:

$users = App\User::all();return $users->toArray();

序列化为 JSON

方法 toJson 可以把模型转化成 JSON。和方法 toArray 一样, toJson 方法也是递归的,因此所有属性和关联都会转化成 JSON, 你还可以指定由 PHP 支持的 JSON 编码选项:

$user = App\User::find(1);
return $user->toJson();
return $user->toJson(JSON_PRETTY_PRINT);

也可以把模型或集合转成字符串,方法 toJson 将自动调用:

$user = App\User::find(1);
return (string) $user;

由于模型和集合在转化为字符串的时候会转成 JSON, 因此可以在应用的路由或控制器中直接返回 Eloquent 对象:

Route::get('users', function () {
    return App\User::all();
  });

隐藏 JSON 属性

有时要将模型数组或 JSON 中的某些属性进行隐藏,比如密码,则可以在模型中添加 $hidden 属性:

<?php
    namespace App;
    use Illuminate\Database\Eloquent\Model;
    class User extends Model{    
    /**
     * 数组中的属性会被隐藏。
     *
     * @var array
     */  
     protected $hidden = ['password'];
   }

{note} 隐藏关联时,需使用关联的方法名。

此外,也可以使用属性 $visible 定义一个模型数组和 JSON 可见的白名单。转化后的数组或 JSON 不会出现其他的属性:

<?phpnamespace App;
    use Illuminate\Database\Eloquent\Model;
    class User extends Model{   
     /**
     * 数组中的属性会被展示。
     *
     * @var array
     */  
     protected $visible = ['first_name', 'last_name'];
   }

临时修改可见属性

如果需要在一个模型实例中显示隐藏的属性,就可以使用 makeVisible 方法。方法 makeVisible 返回模型实例:

return $user->makeVisible('attribute')->toArray();

相应地,需要在一个模型实例中隐藏可见的属性,则可以使用 makeHidden 方法。

return $user->makeHidden('attribute')->toArray();

追加 JSON 值

有时,需要在数组或 JSON 中添加一些数据库没有字段对应的属性。 要实现这个功能,先为其定义一个访问器:

<?php
    namespace App;
    use Illuminate\Database\Eloquent\Model;
    class User extends Model{    
    /**
     * 为用户获取管理员标识。
     *
     * @return bool
     */   
     public function getIsAdminAttribute()  
       {      
         return $this->attributes['admin'] == 'yes';  
       }
    }

然后,在模型属性 appends 中添加该属性名。注意,尽管访问器使用「驼峰命名法」方式定义,但是属性名通常以「蛇形命名法」方式引用。

<?php
    namespace App;
    use Illuminate\Database\Eloquent\Model;
    class User extends Model{    
    /**
     * 追加到模型数组表单的访问器。
     *
     * @var array
     */   
    protected $appends = ['is_admin'];
  }

使用 append 方法追加属性后,它将包含在模型的数组和 JSON 中。 appends 数组中的属性也将遵循模型上配置的 visiblehidden 设置。

运行时追加

在单个模型实例上,使用方法 append 追加属性,或者,使用方法 setAppends 重写整个追加属性的数组:

return $user->append('is_admin')->toArray();
return $user->setAppends(['is_admin'])->toArray();

序列化日期

自定义任意属性的日期格式

可以在 Eloquent 的 属性类型转换 中单独为日期属性自定义日期格式:

protected $casts = [
    'birthday' => 'date:Y-m-d',    
    'joined_at' => 'datetime:Y-m-d H:00',
  ];

Carbon 全局自定义

Laravel 扩展了 Carbon 日期库这为 Carbon 的 JSON 序列化提供了便利。要自定义所有 Carbon 日期在整个应用中的序列化,可以使用 Carbon::serializeUsing 方法。方法 serializeUsing 接受一个闭包,该闭包返回一个字符串形式的日期。

<?php
    namespace App\Providers;
    use Illuminate\Support\Carbon;
    use Illuminate\Support\ServiceProvider;
    class AppServiceProvider extends ServiceProvider{   
     /**
     * 执行注册后,启动服务
     *
     * @return void
     */    
     public function boot()  
       {     
          Carbon::serializeUsing(function ($carbon) {   
                   return $carbon->format('U');       
                 });   
          }   
     /**
     * 在服务容器中注册绑定
     *
     * @return void
     */   
     public function register()  
       {      
         //   
        }
     }
本文章首发在 LearnKu.com 网站上。