Laravel5.1学习笔记23 Eloquent 序列化
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 toArray
method. 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 toJson
method 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 序列化的更多相关文章
- Laravel5.1学习笔记22 Eloquent 调整修改
Eloquent: Mutators Introduction Accessors & Mutators Date Mutators Attribute Casting Introductio ...
- Ext.Net学习笔记23:Ext.Net TabPanel用法详解
Ext.Net学习笔记23:Ext.Net TabPanel用法详解 上面的图片中给出了TabPanel的一个效果图,我们来看一下代码: <ext:TabPanel runat="se ...
- [原创]java WEB学习笔记23:MVC案例完整实践(part 4)---模糊查询的设计与实现
本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...
- Linux下汇编语言学习笔记23 ---
这是17年暑假学习Linux汇编语言的笔记记录,参考书目为清华大学出版社 Jeff Duntemann著 梁晓辉译<汇编语言基于Linux环境>的书,喜欢看原版书的同学可以看<Ass ...
- Laravel5.1学习笔记18 数据库4 数据填充
简介 编写数据填充类 使用模型工厂类 调用额外填充类 执行填充 #简介 Laravel includes a simple method of seeding your database with t ...
- Python学习笔记23:Django构建一个简单的博客网站(一个)
在说如何下载和安装Django,本节将重点讨论如何使用Django站点. 一 新建project 命令:django-admin startproject mysite # 有的须要输入:django ...
- Kali学习笔记23:Web渗透简介
文章的格式也许不是很好看,也没有什么合理的顺序 完全是想到什么写一些什么,但各个方面都涵盖到了 能耐下心看的朋友欢迎一起学习,大牛和杠精们请绕道 我这里先说几句: 其实从缓冲区溢出到Web渗透之间还有 ...
- Java学习笔记42(序列化流)
对象中的数据,以流的形式,写入到文件中保存 过程称为写出对象,对象的序列化 ObjectOutputStream将对象写到文件中,实现序列化 在文件中,以流的形式,将对象读取出来, 读取对象,对象的反 ...
- C++学习笔记23,类内函数重载
该博文仅用于交流学习.请慎用于不论什么商业用途,本博主保留对该博文的一切权利. 博主博客:http://blog.csdn.net/qq844352155 转载请注明出处: 在一个类内,最常见的就是构 ...
随机推荐
- COGS2479(四维偏序)
题意:给定一个有n个元素的序列,元素编号为1~n,每个元素有三个属性a,b,c,求序列中满足i<j且ai<aj且bi<bj且ci<cj的数对(i,j)的个数. 分析:cdq分治 ...
- Java中如何获取spring中配置的properties文件内容
有2种方式: 一. 1.通过spring配置properties文件 [java] <bean id="propertyConfigurer" class=&qu ...
- dstat用法;利用awk求dstat所有列每列的和;linux系统监控
安装:yum install -y dstat dstat命令是一个用来替换vmstat.iostat.netstat.nfsstat和ifstat这些命令的工具,是一个全能系统信息统计工具.与sys ...
- DOM对象与jquery对象的互相转换
一開始总是对DOM对象和jQuery对象搞不清楚.如今对此做一下总结: DOM 对象:文档对象模型.每一份DOM都能够看作一棵树.像ul,li ol dl p h1 等等都是DOM元素节点.能 ...
- 017 SSH
Router>en Router#config t Enter configuration commands, one per line. End with CNTL/Z. Router(co ...
- win7如何更改语言教程
一.首先从桌面左下角的开始菜单中找到“控制面板”,然后打开,如下图所示: 打开电脑控制面板 二.进入控制面板之后,我们再进入“时钟.语言和区域”设置,如下图所示: 电脑语言改成英文方法 三.进入电脑语 ...
- spring test---restful与文件上传
spring提供了大量经常使用的功能測试,如文件上传.restful风格url訪问.以下介绍主要介绍下test中经常使用功能的使用方法: 首先能够静态导入类.方便在測试类中使用,导入的类有 impor ...
- 连接App.config
ConfigurationManager.AppSettings["AdminName"]; 连接App.config的字符
- Mali GPU OpenGL ES 应用性能优化--基本方法
1. 经常使用优化工具 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvTXlBcnJvdw==/font/5a6L5L2T/fontsize/400/fil ...
- openstack-wsgi的route中添加api流程具体解释(os-networks)添加
感谢朋友支持本博客.欢迎共同探讨交流,因为能力和时间有限,错误之处在所难免.欢迎指正! 如有转载,请保留源作者博客信息. Better Me的博客:blog.csdn.net/tantexian 如需 ...