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. ViewFlipper实现ViewPager的页面切换效果

    activity_main.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android&qu ...

  2. VMware实用技巧

    1.VM快照管理 这个功能实在太常用,不用我多废话.这里只是提醒一下还没有用过快照的同学,赶紧的给自己的VM保存点快照吧,这样VM里的系统出了问题或是有其它需要很容易让你还原到原来的某个点,这功能可比 ...

  3. android仿qq空间、微信朋友圈图片展示

    废话不多说,先上效果图 由于近期须要做朋友圈功能,所以在此记录一下,事实上非常多人不明确的一点应该是在图片的排列上面吧,不规则的排列,事实上非常easy的.就是一个GridView.然而你xml光光写 ...

  4. oralce之复杂查询举例

    表结构: S(SNO,SNAME) 代表 学号.学生姓名: C(CNO,CNAME,CTEACHER) 代表 课号,课程名称.授课老师 SC(SNO,CNO,SCGRADE) 代表 学号.课号.课程成 ...

  5. HDU 4869 Turn the pokers (2014多校联合训练第一场1009) 解题报告(维护区间 + 组合数)

    Turn the pokers Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) ...

  6. C语言之基本算法25—牛顿迭代法求方程近似根

    //牛顿迭代法! /* ============================================================ 题目:用牛顿迭代法求解3*x*x*x-2*x*x-16 ...

  7. 【剑指Offer学习】【面试题31:连续子数组的最大和】

    题目:输入一个整型数组,数组里有正数也有负数.数组中一个或连续的多个整数组成一个子数组.求全部子数组的和的最大值.要求时间复杂度为O(n). 样例说明: 比如输入的数组为{1, -2, 3, 10, ...

  8. [Qt总结篇]终端远程升级client

    环境: QT4.8.5 for Windows(Qt Creator+MinGW) 一.写在前面: 1.深度:鉴于C/C++的功底还远远不足,个人主要精力还是学习C/C++,所以没打算继续深入研究Qt ...

  9. Bridge Page

    http://www.zzbaike.com/wiki/%E6%A1%A5%E9%A1%B5 桥页(Bridge Page),又叫“门页”(Doorway/Portal/Jump/Entry Page ...

  10. Ubuntu下Zabbix服务器监控工具部署

    Ubuntu下Zabbix服务器监控工具部署 一 安装安装Apache.Mysql.Php.zabbix sudo apt-get update sudo apt-get install apache ...