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