Eloquent: Serialization

Introduction

When building JSON APIs, you will often need to convert your models and relationships to arrays or JSON. Eloquent includes convenient methods for making these conversions, as well as controlling which attributes are included in your serializations.

Basic Usage

Converting A Model To An Array

To convert a model and its loaded relationships to an array, you may use the toArraymethod. This method is recursive, so all attributes and all relations (including the relations of relations) will be converted to arrays:

$user = App\User::with('roles')->first();

return $user->toArray();

You may also convert collections to arrays:

$users = App\User::all();

return $users->toArray();
Converting A Model To JSON

To convert a model to JSON, you may use the toJson method. Like toArray, the toJsonmethod is recursive, so all attributes and relations will be converted to JSON:

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

return $user->toJson();

Alternatively, you may cast a model or collection to a string, which will automatically call the toJson method:

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

return (string) $user;

Since models and collections are converted to JSON when cast to a string, you can return Eloquent objects directly from your application's routes or controllers:

Route::get('users', function () {
return App\User::all();
});

Hiding Attributes From JSON

Sometimes you may wish to limit the attributes, such as passwords, that are included in your model's array or JSON representation. To do so, add a $hidden property definition to your model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = ['password'];
}

Note: When hiding relationships, use the relationship's method name, not its dynamic property name.

Alternatively, you may use the visible property to define a white-list of attributes that should be included in your model's array and JSON representation:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
/**
* The attributes that should be visible in arrays.
*
* @var array
*/
protected $visible = ['first_name', 'last_name'];
}

Appending Values To JSON

Occasionally, you may need to add array attributes that do not have a corresponding column in your database. To do so, first define an accessor for the value:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
/**
* Get the administrator flag for the user.
*
* @return bool
*/
public function getIsAdminAttribute()
{
return $this->attributes['admin'] == 'yes';
}
}

Once you have created the accessor, add the attribute name to the appends property on the model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = ['is_admin'];
}

Once the attribute has been added to the appends list, it will be included in both the model's array and JSON forms. Attributes in the appends array will also respect thevisible and hidden settings configured on the model.

Laravel5.1学习笔记23 Eloquent 序列化的更多相关文章

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

    Eloquent: Mutators Introduction Accessors & Mutators Date Mutators Attribute Casting Introductio ...

  2. Ext.Net学习笔记23:Ext.Net TabPanel用法详解

    Ext.Net学习笔记23:Ext.Net TabPanel用法详解 上面的图片中给出了TabPanel的一个效果图,我们来看一下代码: <ext:TabPanel runat="se ...

  3. [原创]java WEB学习笔记23:MVC案例完整实践(part 4)---模糊查询的设计与实现

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

  4. Linux下汇编语言学习笔记23 ---

    这是17年暑假学习Linux汇编语言的笔记记录,参考书目为清华大学出版社 Jeff Duntemann著 梁晓辉译<汇编语言基于Linux环境>的书,喜欢看原版书的同学可以看<Ass ...

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

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

  6. Python学习笔记23:Django构建一个简单的博客网站(一个)

    在说如何下载和安装Django,本节将重点讨论如何使用Django站点. 一 新建project 命令:django-admin startproject mysite # 有的须要输入:django ...

  7. Kali学习笔记23:Web渗透简介

    文章的格式也许不是很好看,也没有什么合理的顺序 完全是想到什么写一些什么,但各个方面都涵盖到了 能耐下心看的朋友欢迎一起学习,大牛和杠精们请绕道 我这里先说几句: 其实从缓冲区溢出到Web渗透之间还有 ...

  8. Java学习笔记42(序列化流)

    对象中的数据,以流的形式,写入到文件中保存 过程称为写出对象,对象的序列化 ObjectOutputStream将对象写到文件中,实现序列化 在文件中,以流的形式,将对象读取出来, 读取对象,对象的反 ...

  9. C++学习笔记23,类内函数重载

    该博文仅用于交流学习.请慎用于不论什么商业用途,本博主保留对该博文的一切权利. 博主博客:http://blog.csdn.net/qq844352155 转载请注明出处: 在一个类内,最常见的就是构 ...

随机推荐

  1. Java度线程——生产消费问题

    /*JDK1.4版本:生产者,消费者.多生产者,多消费者的问题.if判断标记,只有一次,会导致不该运行的线程运行了.出现了数据错误的情况.while判断标记,解决了线程获取执行权后,是否要运行! no ...

  2. 洛谷 P1555 尴尬的数字

    P1555 尴尬的数字 题目背景 Bessie刚刚学会了不同进制数之间的转换,但是她总是犯错误,因为她的两个前蹄不能轻松的握住钢笔. 题目描述 每当Bessie将一个数转换成新的进制时,她总会写错一位 ...

  3. 戴尔iDRAC服务器远程控制设置

    对于远程的服务器,我们不能经常性的去机房维护,所以远程控制对于服务器来说就显得至关重要.那么你是用什么方式对服务器进行远程控制呢?远程桌面?还是KVM切换器?NO,你OUT了!如果你用的是戴尔的服务器 ...

  4. Kafka跨集群同步工具——MirrorMaker

    MirrorMaker是为解决Kafka跨集群同步.创建镜像集群而存在的.下图展示了其工作原理.该工具消费源集群消息然后将数据又一次推送到目标集群. watermark/2/text/aHR0cDov ...

  5. java.io.IOException: read failed, socket might closed or timeout, read ret: -1

    近期项目中连接蓝牙之后接收蓝牙设备发出的指令功能,在连接设备之后,创建RfcommSocket连接时候报java.io.IOException: read failed, socket might c ...

  6. Linux操作系统改动PATH的方法

    1. 暂时改动: 使用export.比如#export PATH=$PATH:/etc/apache/bin 2. 针对用户的改动: vi ~/.bash_profile 增加:export PATH ...

  7. 获取Linux磁盘分区的UUID

    在设置fstab自动挂载时,需要填写如下的信息: # <file system> <mount point> <type> <options> < ...

  8. Android处理日期

    近期做一个项目,后台返回的日期是RFC3339格式的.之前没有看到过,当中遇到了几个问题以及解决 1.2015-11-18T14:49:55Z转换 在SimpleDateFormat中给出了几种格式 ...

  9. 跟踪oracle中sql语句运行过程及相关知识拓展

    select * from v$sqlarea; select * from v$sqlarea where first_load_time>'2010-11-27/09:30:00'; 这种方 ...

  10. P2030 遥控车

    P2030 遥控车 2通过 11提交 题目提供者LittleZ 标签二分字符串递推高精洛谷原创 难度尚无评定 提交该题 讨论 题解 记录 最新讨论 暂时没有讨论 题目描述 平平带着韵韵来到了游乐园,看 ...