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. JSP服务器响应

    以下内容引用自http://wiki.jikexueyuan.com/project/jsp/server-response.html: 当一个Web服务器响应浏览器的HTTP请求时,响应通常包括一个 ...

  2. Office高级威胁漏洞在野利用分析

    高级威胁漏洞背景 在高级威胁攻击中,黑客远程投递入侵客户端最喜欢的漏洞是office文档漏洞,就在刚刚结束不久的黑帽子大会上,最佳客户端安全漏洞奖颁给了CVE-2017-0199漏洞,这个漏洞是时下o ...

  3. IPv6 Ready Logo测试环境搭建

    最新的IPv6 Ready Logo tool http://interop.ipv6.org.tw/CERouter/ 安装最新的tool,要求FreeBSD在8.0以上 uname  -r查看版本 ...

  4. IOS-Storyboard控制器切换之Modal(1)

    Modal模式是指模态切换.新开的界面会挡住之前的界面,使之不能获取焦点. 创建一个singleView模板的程序,打开storyboard文件.拖动2个UIViewController到界面中.按住 ...

  5. [转] Ubuntu/Linux Mint/Debian 安装 Java 8

    本PPA由webupd8制作,支持Ubuntu .04以及对应的Linux Mint版本,Oracle Java 8包提供JDK8 和 JRE8. sudo add-apt-repository pp ...

  6. 利用栈Stack实现队列(Queue)

    实现说明: 入队时,将元素压入s1; 出队时,推断s2是否为空,如不为空,则直接弹出顶元素:如为空.则将s1的元素逐个"倒入"s2.把最后一个元素弹出并出队; 这个思路,避免了重复 ...

  7. (一)Java 入门教程

    Java 入门教程 Java 是由Sun Microsystems公司于1995年5月推出的高级程序设计语言. Java可运行于多个平台,如Windows, Mac OS,及其他多种UNIX版本的系统 ...

  8. redis 的部分配置

    linux 安装: yum install redis 修改redis配置: 配置文件位于/etc/redis.conf. 作为守护进程运行(默认no) # 默认情况下 redis 不是作为守护进程运 ...

  9. PHP博客项目-gai

    XX科技还是米有电话过来,看样子真的是黄了.这段时间都没有好好学习,经历了两次稀里糊涂的面试,特别是第二次,让我感觉自己之前学的东西都已经忘了,本来就学的不多,也不扎实,还一忘...看了是真的要开始着 ...

  10. POJ1264 SCUD Busters 凸包

    POJ1264 有m个国家(m<=20)对每个国家给定n个城镇 这个国家的围墙是保证围住n个城镇的周长最短的多边形 必然是凸包 进行若干次导弹发射 落到一个国家内则国家被破坏 最后回答总共有多少 ...