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 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 序列化的更多相关文章
- 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 转载请注明出处: 在一个类内,最常见的就是构 ...
随机推荐
- CentOS 7 es搭建测试
搭建本地yum repo pass 指定特定repo 安装,比如安装wget.(指定特定repo 是为了从最快的repo安装) yum --disablerepo=\* --enablerepo=os ...
- M2Crypto
M2Crypto = Python + OpenSSL + SWIG M2Crypto is a crypto and SSL toolkit for Python. 上面是M2Crypto的READ ...
- html实现类似excel的复杂表格,及导出到excel
1. excellentexport.js https://github.com/jmaister/excellentexport/tree/2.0.3 2.fiddle example https ...
- C语言事实上不简单:数组与指针
之前在写C的时候,没怎么留意数组.就这么定义一个.然后颠来倒去的使用即可了.只是后来碰到了点问题.解决后决定写这么一篇博客,数组离不开指针.索性就放一起好了. 如今我定义了一个数组:int cc[10 ...
- 制作svg动画
要实现一步一步画出来一个图片,css3做不到吧.除非一张张的图片定时显示.想不到别的招了.如今用的是一个插件,做了一个svg动画. 插件地址:http://lazylinepainter.info/ ...
- 小白学开发(iOS)OC_ 字符串的获取 (2015-08-11)
// // main.m // 字符串的获取 // // Created by admin on 15/8/13. // Copyright (c) 2015年 admin. All righ ...
- Java总结之网络
[网络基础概念] 什么是计算机网络: 把分布在不同地理区域的计算机与专门的外部设备用通信线路互连成一个规模大.功能强的网络系统,从而使众多的计算机能够方便的互相传递信息,共享硬件.软件.数据信息等资源 ...
- c语言有头循环单链表
/************************************************************************* > File Name: singleLin ...
- C++之桟的应用---括号匹配
刚開始学习数据结构.用桟写了一个经典的应用,括号匹配. 算法思路: 输入字符串时.将 '(' , '[' 压入桟.遇到 ')' ']' 时,再栈顶出桟.进行括号匹配.假设成功匹配.则继续进行.否 ...
- 内容可编辑且随内容自增长的div
<!DOCTYPE HTML> <html> <head> <title></title> <meta http-equiv=&quo ...