laravel 之 Eloquent 模型修改器和序列化示例
修改器
获取
<?php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { public function getFirstNameAttribute($value) { return ucfirst($value); } }
使用 Laravel 加密器 来加密一个被保存在数据库中的值,当你从 Eloquent 模型访问该属性时该值将被自动解密。
$user = App\User::find(1); $firstName = $user->first_name;
修改
public function setFirstNameAttribute ($value) { $this->attributes['first_name'] = strtolower($value); }
$user = App\User::find(1); $user->first_name = 'Sally';
日期转化器
<?php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model{ protected $dates = [ 'created_at', 'updated_at', 'deleted_at' ]; }
$user = App\User::find(1); $user->deleted_at = Carbon::now(); $user->save();
可在属性上使用任何 Carbon 方法:
$user = App\User::find(1); echo $user->deleted_at->getTimestamp();
设置时间格式
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Flight extends Model { protected $dateFormat = 'U'; }
属性类型转化
<?php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { protected $casts = [ 'is_admin' => 'boolean', ]; }
现在当你访问 is_admin 属性时,它将会被转换成布尔值,即便保存在数据库里的值是一个整数:
$user = App\User::find(1); if ($user->is_admin) { // }
支持的转换的类型有:
integer
real
float
double
string
boolean
object
array
collection
date
datetime
timestamp
# protected $casts = [ # 'options' => 'array', # ]; $user = App\User::find(1); $options = $user->options; $options['key'] = 'value'; $user->options = $options; $user->save();
序列化模型或集合
序列化成数组
$user = App\User::with('roles')->first(); return $user->toArray();
序列化成 JSON
$user = App\User::find(1); return $user->toJson(); // 或者 return (string) $user; // 自动调用 toJson // 或者 return App\User::all();
隐藏来自 json 的属性
<?php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { protected $hidden = ['password']; }
<?php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { protected $visible = ['first_name', 'last_name']; }
临时隐藏
return $user->makeVisible('attribute')->toArray(); return $user->makeHidden('attribute')->toArray();
添加参数到 json 中
<?php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { protected $appends = ['is_admin']; }
# 在 appends 数组中的属性也遵循模型中 visible 和 hidden 设置 public function getIsAdminAttribute() { return $this->attributes['is_admin'] == 'yes'; }
以上这篇laravel 之 Eloquent 模型修改器和序列化示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。
赞 (0)