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. mysql利用timestamp来进行帖子排序

    select * from table order by timestamp descorder by 该列 desc timestamp字段也可以用来排序,对应Java类型的.net.timesta ...

  2. Chains (链 )

    Indy 中的工作队列系统,调度器,和链引擎都被叫做链. 当使用链的时候,一个基于链的 IOHandler 存储工作项目到有关的工作队列中.在一个工作单元被完成以前,执行这个工作单元的纤程是无法做其它 ...

  3. 离线安装Cloudera Manager5.3.4与CDH5.3.4

    文章转载:http://www.aboutyun.com/thread-14024-1-1.html 前期准备工作(系统环境搭建) 操作系统:CentOS 6.5 x64 CPU*2 64G 300G ...

  4. [Typescript Kaop-ts] Use AOP in Vue Components with TypeScript and Kaop-ts

    Aspect Oriented Programming, AOP, allows to reuse logic across an entire app in a very neat way, dec ...

  5. android中单元測试中的断言assert的使用与扩展

    首先看一组对照,比方说我们要測试的结果是一个Linearlaout AssertJ Android: assertThat(layout).isVisible() .isVertical() .has ...

  6. Android--Activity在跳转时携带数据

    首先看看两种传递方法演示样例:(一个简单姻缘计算器) 主Activity import android.os.Bundle; import android.app.Activity; import a ...

  7. 基于cocos2d-x的跑酷游戏,不同高度地面的碰撞检測demo,有兴趣能够看一看

    1. demo大致分为4个模块: 地图,角色,障碍 逻辑检測认为和不同高度地面的碰撞.1次跳和2连跳的实现. 代码链接:http://download.csdn.net/detail/zangleng ...

  8. 省市联动选择的一个demo,利用vue+webpack+amaze-vue实现省市区联动选择组件

    https://github.com/sunshineJi/vue-city-picker

  9. 斜率优化专题1——bzoj 1597 [Usaco2008 Mar] 土地购买 题解

    转载请注明:http://blog.csdn.net/jiangshibiao/article/details/24387147 [原题] 1597: [Usaco2008 Mar]土地购买 Time ...

  10. javascript闭包具体解释

    今天我们从内存结构上来解说下 javascript中的闭包概念. 闭包:是指有权訪问另外一个函数作用域中的变量的函数. 创建闭包的常见方式就是在一个函数内部创建另外一个函数. 在javascript中 ...