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. mac idea快捷键(部分常用)

    shift+F6重命名 shift+enter 换到下一行 shift+F8等同eclipse的f8跳到下一个断点,也等同eclipse的F7跳出函数 F8等同eclipse的f6跳到下一步F7等同e ...

  2. JSP国际化设置

    以下内容引用自http://wiki.jikexueyuan.com/project/jsp/internationalization.html: 国际化(i18n):这意味着可以使网站根据访问者的语 ...

  3. 怎么让Excel显示时间时候能把秒显示出来

    Excel显示时间一般只显示年月日小时分钟怎么能够把秒也显示出来既如下显示 2007-04-11 12:00:00 将单元格格式设为"自定义",在"类型"框中输 ...

  4. java List.add操作可以指定位置

    java List.add操作可以指定位置,addAll也可以指定: 使用: public class Test02 { public static void main(String[] args) ...

  5. 免费好用的Microsoft iSCSI Software Target 3.3

    我们在搭建Windows群集的时候往往会使用到IP-SAN.但是面对昂贵的硬件IP-SAN,我们在学习和实验的环境中更加多的用到的往往是软件模拟的IP-SAN.今天就给大家介绍一个微软出品的免费iSC ...

  6. Tomcat启动一半闪退问题解决

    近期刚刚接触Tomcat.对其还不是非常了解. 在这几天,遇到一个Tomcat启动闪退的问题.通过查阅各种资料.算是完美解决.在此分享给朋友们. 首先.确定你的问题在哪里.有两个方法,你能够通过日志去 ...

  7. javaweb_page指令

    jsp指令: 1.作用:jsp指令是为jsp引擎设计的.他们并不直接产生不论什么课件输出.而是告诉引擎怎样处理jsp页面中的其余部分 2.jsp指令包含:page指令.include指令,taglib ...

  8. bootstrap 时间控件

    近期使用了bootstrap的UI感觉确实非常美丽,非常值得学习和使用. 以下先简单了解下bootstrap的时间控件. 这个时间控件使用起来还是很的简单.仅仅须要引入主要的css和js就能够了 须要 ...

  9. JsonArray和JsonObject的使用

    import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class JsonTest { public static v ...

  10. centos部署jenkins

    1. 实验环境:   操作系统: CentOS Linux release 7.2.1511 (Core) 软件版本: jdk-8u60-linux-x64    apache-tomcat-9.0. ...