Laravel5.1学习笔记22 Eloquent 调整修改

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();
时间: 2024-08-13 01:37:07

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

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

Eloquent: Serialization Introduction Basic Usage Hiding Attributes From JSON Appending Values To JSON Introduction When building JSON APIs, you will often need to convert your models and relationships to arrays or JSON. Eloquent includes convenient m

EasyARM i.mx28学习笔记——根文件系统rootfs修改和烧写

0 前言 本文详细说明如何修改和制作根文件系统,包括修改根文件系统中的配置文件:在根文件系统中加入可执行文件,最后通过uboot tftp方式烧录根文件系统和镜像. [相关博文] [EasyARM i.mx28学习笔记--文件IO方式操作GPIO] [EasyARM i.mx28学习笔记--安装和使用tftp] [EasyARM i.mx28学习笔记--minicom配置和使用] [EasyARM i.mx28学习笔记--通过modbus tcp控制GPIO] 1 准备 若使用uboot tft

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

Ext.Net学习笔记22:Ext.Net Tree 用法详解 上面的图片是一个简单的树,使用Ext.Net来创建这样的树结构非常简单,代码如下: <ext:TreePanel runat="server"> <Root> <ext:Node Text="根节点" Expanded="true"> <Children> <ext:Node Text="节点1" Expand

C++学习笔记22,普通函数重载(1)

转载请注明出处:http://blog.csdn.net/qq844352155/article/details/31353325 该博文仅用于交流学习,请慎用于任何商业用途,本博主保留对该博文的一切权利. 博主博客:http://blog.csdn.net/qq844352155 什么是方法重载? 方法重载也可以说是函数重载,函数的多态性. 具体来说就是将函数或者方法的名称用于多个函数,但是参数的类型或者参数的数目不同. 在这篇blog里面我只讨论类外函数的重载. 例如一个简单的例子: #in

python基础教程_学习笔记22:数据库支持

数据库支持 python数据库API 支持sql标准的可用数据库有很多,其中多数在python中都有对应的客户端模块. 全局变量 python DB API的模块特性 变量名 用途 apilevel 所使用的python db api版本 threadsafety 模块的线程安全等级 paramstyle 在sql查询中使用的参数风格 异常 异常 超类 描述 StandardError 所有异常的泛型基类 Warning StandardError 在非致命错误发生时引发 Error Stand

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

自从2015年花了2个多月时间把Hadoop1.x的学习教程学习了一遍,对Hadoop这个神奇的小象有了一个初步的了解,还对每次学习的内容进行了总结,也形成了我的一个博文系列<Hadoop学习笔记系列>.其实,早在2014年Hadoop2.x版本就已经开始流行了起来,并且已经成为了现在的主流.当然,还有一些非离线计算的框架如实时计算框架Storm,近实时计算框架Spark等等.相信了解Hadoop2.x的童鞋都应该知道2.x相较于1.x版本的更新应该不是一丁半点,最显著的体现在两点: (1)H

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

在azure vm上安装了CRM 2015后 Dynamic CRM 2015学习笔记(1)Azure 上安装 CRM 2015, 发现了一个问题,那就是在设置 ->自定义项 –> 开发人员资源 里面的几个ulr(发现服务.组织服务和组织数据服务)都不对,显示的都是http://机器名/XRMServices/2011/ -, 但这个url是访问不了的,正确的url应该是 http://xxx.cloudapp.net/XRMServices/2011/ - 下面介绍如何修改成正确的url.

【安全牛学习笔记】选择和修改EXP

选择和修改EXP 网公开的EXP代码 选择可信赖的EXP源 Exploit-db SecruityFocus Searchsploit 有能力修改EXP(Python.Perl.Ruby.C.C++...) www.securityfocus.com 选择和修改EXP 646.c 类unix坏境下编译 返回地址与我们的环境不符 反弹shell硬编码了回链IP地址 缓冲区偏移量与我们的环境不符 目标IP硬编码 [email protected]:~# searchsploit slmail ---

Linux学习笔记(22) Linux启动管理

1. 系统运行级别 运行级别 含义 0 关机 1 单用户模式,可想象为windows的安全模式,主要用于系统修复 2 不完全的命令行模式,不含NFS服务 3 完全的命令行模式,就是标准字符界面 4 系统保留 5 图形模式 6 重启动 (1) 运行级别命令 runlevel #查看运行级别命令 N表示进入3前面的级别 init 运行级别 #改变运行级别命令 (2) 系统默认运行级别 在配置文件/etc/inittab中进行修改即可 id:3:initdefault: #系统开机后直接进入哪个运行级