Eloquent: Mutators

Introduction

Accessors and mutators allow you to format Eloquent attributes when retrieving them from a model or setting their value. For example, you may want to use the Laravel encrypter to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model.

In addition to custom accessors and mutators, Eloquent can also automatically cast date fields to Carbon instances or even cast text fields to JSON.

Accessors & Mutators

Defining An Accessor

To define an accessor, create a getFooAttribute method on your model where Foo is the "camel" cased name of the column you wish to access. In this example, we'll defined an accessor for the first_name attribute. The accessor will automatically be called by Eloquent when attempting to retrieve the value of first_name:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
/**
* Get the user's first name.
*
* @param string $value
* @return string
*/
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
}

As you can see, the original value of the column is passed to the accessor, allowing you to manipulate and return the value. To access the value of the mutator, you may simply access the first_name attribute:

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

$firstName = $user->first_name;
Defining A Mutator

To define a mutator, define a setFooAttribute method on your model where Foo is the "camel" cased name of the column you wish to access. So, again, let's define a mutator for the first_name attribute. This mutator will be automatically called when we attempt to set the value of the first_name attribute on the model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
/**
* Set the user's first name.
*
* @param string $value
* @return string
*/
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = strtolower($value);
}
}

The mutator will receive the value that is being set on the attribute, allowing you to manipulate the value and set the manipulated value on the Eloquent model's internal$attributes property. So, for example, if we attempt to set the first_name attribute to Sally:

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

$user->first_name = 'Sally';

In this example, the setFirstNameAttribute function will be called with the value Sally. The mutator will then apply the strtolower function to the name and set its value in the internal $attributes array.

Date Mutators

By default, Eloquent will convert the created_at and updated_at columns to instances ofCarbon, which provides an assortment of helpful methods, and extends the native PHPDateTime class.

You may customize which fields are automatically mutated, and even completely disable this mutation, by overriding the $dates property of your model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['created_at', 'updated_at', 'disabled_at'];
}

When a column is considered a date, you may set its value to a UNIX timestamp, date string (Y-m-d), date-time string, and of course a DateTime / Carbon instance, and the date's value will automatically be correctly stored in your database:

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

$user->disabled_at = Carbon::now();

$user->save();

As noted above, when retrieving attributes that are listed in your $dates property, they will automatically be cast to Carbon instances, allowing you to use any of Carbon's methods on your attributes:

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

return $user->disabled_at->getTimestamp();

Attribute Casting

The $casts property on your model provides a convenient method of converting attributes to common data types. The $casts property should be an array where the key is the name of the attribute being cast, while the value is the type you wish to cast to the column to. The supported cast types are: integer, real, float, double, string, boolean,object and array.

For example, let's cast the is_admin attribute, which is stored in our database as an integer (0 or 1) to a boolean value:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'is_admin' => 'boolean',
];
}

Now the is_admin attribute will always be cast to a boolean when you access it, even if the underlying value is stored in the database as an integer:

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

if ($user->is_admin) {
//
}
Array Casting

The array cast type is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a TEXT field type that contains serialized JSON, adding the array cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'options' => 'array',
];
}

Once the cast is defined, you may access the options attribute and it will automatically be deserialized from JSON into a PHP array. When you set the value of the optionsattribute, the given array will automatically be serialized back into JSON for storage:

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

$options = $user->options;

$options['key'] = 'value';

$user->options = $options;

$user->save();

Laravel5.1学习笔记22 Eloquent 调整修改的更多相关文章

  1. Laravel5.1学习笔记23 Eloquent 序列化

    Eloquent: Serialization Introduction Basic Usage Hiding Attributes From JSON Appending Values To JSO ...

  2. 【转】Pandas学习笔记(三)修改&添加值

    Pandas学习笔记系列: Pandas学习笔记(一)基本介绍 Pandas学习笔记(二)选择数据 Pandas学习笔记(三)修改&添加值 Pandas学习笔记(四)处理丢失值 Pandas学 ...

  3. Ext.Net学习笔记22:Ext.Net Tree 用法详解

    Ext.Net学习笔记22:Ext.Net Tree 用法详解 上面的图片是一个简单的树,使用Ext.Net来创建这样的树结构非常简单,代码如下: <ext:TreePanel runat=&q ...

  4. SQL反模式学习笔记22 伪键洁癖,整理数据

    目标:整理数据,使不连续的主键Id数据记录变的连续. 反模式:填充断档的数据空缺. 1.不按照顺序分配编号 在插入新行时,通过遍历表,找到的第一个未分配的主键编号分配给新行,来代替原来自动分配的伪主键 ...

  5. Hadoop学习笔记—22.Hadoop2.x环境搭建与配置

    自从2015年花了2个多月时间把Hadoop1.x的学习教程学习了一遍,对Hadoop这个神奇的小象有了一个初步的了解,还对每次学习的内容进行了总结,也形成了我的一个博文系列<Hadoop学习笔 ...

  6. Dynamic CRM 2015学习笔记(4)修改开发人员资源(发现服务、组织服务和组织数据服务)url地址及组织名

    在azure vm上安装了CRM 2015后 Dynamic CRM 2015学习笔记(1)Azure 上安装 CRM 2015, 发现了一个问题,那就是在设置 ->自定义项 –> 开发人 ...

  7. [原创]java WEB学习笔记22:MVC案例完整实践(part 3)---多个请求对应一个Servlet解析

    本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...

  8. ‎Cocos2d-x 学习笔记(22) TableView

    [Cocos2d-x 学习笔记 ]目录 1. 简介 TableView直接继承了ScrollView和ScrollViewDelegate.说明TableView能实现ScrollView拖动cont ...

  9. Laravel5.1学习笔记18 数据库4 数据填充

    简介 编写数据填充类 使用模型工厂类 调用额外填充类 执行填充 #简介 Laravel includes a simple method of seeding your database with t ...

随机推荐

  1. 思科CISCO 交换机命名规则

      思科交换机的命名规则要比路由的命名规则复杂, 看下这些:WS-C2960-24TC-L .WS-C2950G-24-EI-DC .WS-C2960-24TT-L .WS-C3750G-24TS-E ...

  2. MongoDB小结04 - update【$inc】

    update方法很强大,它有两个参数,一是查询文档,用来找出需要更新的文档,另一个是修改器(modifier)文档,描述对找到的文档做哪些修改. 亮点 更新操作是原子的,若两个更新同时发生,先到达服务 ...

  3. 链表倒置,这个还是考验仔细程度,第一遍还没做对 —— 剑指Offer

    https://www.nowcoder.net/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId=11168&tPage= ...

  4. sqlite自己主动更新数据库

    写一个类继承自  SQLiteOpenHelper 系统会自己主动加入构造方法. onCreate方法.onUpgrade方法 当数据库里面数据或者表结构有所修改时.咱们须要升级数据库 这个时候.版本 ...

  5. 硬件十万个为什么——运放篇(五)PCB设计技巧

    1.在PCB设计时,芯片电源处旁路滤波等电容应尽可能的接近器件.典型距离是小于3MM 2.运算放大器芯片电源处的小陶瓷旁路电容在放大器处于输入高频信号时能够为放大器的高频特性提供能量电容值的选择依据输 ...

  6. S5P4418裸机开发系列教程--源代码下载

    S5P4418裸机系列教程之stdio S5P4418裸机系列教程之shell命令行 S5P4418裸机系列教程之串口回显 S5P4418裸机系列教程之复位測试 S5P4418裸机系列教程之led跑马 ...

  7. mongodb配置复制集replset

    Mongodb的replication主要有两种:主从和副本集(replica set).主从的原理和mysql类似,主节点记录在其上的所有操作oplog,从节点定期轮询主节点获取这些操作,然后对自己 ...

  8. ZOJ 3609 Modular Inverse(扩展欧几里德)

    题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=4712 The modular modular multiplicat ...

  9. Poj 3233 矩阵快速幂,暑假训练专题中的某一道题目,矩阵快速幂的模板

    题目链接  请猛戳~ Description Given a n × n matrix A and a positive integer k, find the sum S = A + A2 + A3 ...

  10. go 安装方法

    wget https://storage.googleapis.com/golang/go1.5.linux-amd64.tar.gz sudo tar -C /usr/local -xzf go1. ...