在使用链式操作的时候,例如:

return $user->avatar->url;
如果 $user->avatar 为 null,就会引起 (E_ERROR) Trying to get property 'url' of non-object 错误。

1. 常规方法是使用 isset 加以判断:
if(isset($user->avatar->url))
return $user->avatar->url;
else
return 'defaultUrl';
如果在 blade 模板的 echo 中,可以使用:

{{ $user->avatar->url or 'defaultUrl' }}
上述代码会被 Blade 引擎解析为:

echo e(isset($user->avatar->url) ? $user->avatar->url : 'defaultUrl');
Laravel 5.7 已经取消了这个特性。详见:https://github.com/laravel/framework/pull/... 。感谢 [[[[[[@jltxwesley](https://learnku.com/users/28596)](https://learnku.com/users/28596)](https://learnku.com/users/28596)](https://learnku.com/users/28596)](https://learnku.com/users/28596)](https://learnku.com/users/28596) 提醒。

2. PHP7 可以使用 ?? (NULL 合并操作符) :
// 如果 $user->avatar->url 为 null, 返回 'defaultUrl'
return $user->avatar->url ?? 'defaultUrl';
3. Laravel 5.5 及以上可以使用 optional 辅助函数:
/**
* 如果给定的对象是 null , 那么属性和方法会简单地返回 null 而不是产生一个错误:
*/
return optional($user->avatar)->url;
详见 辅助函数《Laravel 5.5 中文文档》

Laravel 5.7 中,optional 函数还可以接受 匿名函数 作为第二个参数:

/**
* 如果第一个参数不为 null, 则调用闭包
* 详见 https://laravel\com/docs/5.7/helpers#method-optional
*/
return optional(User::find($id), function ($user) {
return new DummyUser;
});
4. 使用 object_get 辅助函数
return object_get($user->avatar, 'url', 'default');
这个函数原意是用来已 . 语法来获取对象中的属性,例如:

return object_get($user, 'avatar.url', 'default');
也可以达到避免 non-object 错误的效果。

if (! function_exists('object_get')) {
/**
* Get an item from an object using "dot" notation.
*
* @param object $object
* @param string $key
* @param mixed $default
* @return mixed
*/
function object_get($object, $key, $default = null)
{
if (is_null($key) || trim($key) == '') {
return $object;
}

foreach (explode('.', $key) as $segment) {
if (! is_object($object) || ! isset($object->{$segment})) {
return value($default);
}

$object = $object->{$segment};
}

return $object;
}
}
详见 https://github.com/laravel/framework/blob/...

感谢 [[[[[@lovecn](https://learnku.com/users/87)](https://learnku.com/users/87)](https://learnku.com/users/87)](https://learnku.com/users/87)](https://learnku.com/users/87) 提供姿势!

5. 使用 data_get 辅助函数
return data_get($user, 'avatar.url', 'default');

return data_get($user, ['avatar', 'url'], 'default');
以 . 语法来获取对象属性或数组元素。

if (! function_exists('data_get')) {
/**
* Get an item from an array or object using "dot" notation.
*
* @param mixed $target
* @param string|array $key
* @param mixed $default
* @return mixed
*/
function data_get($target, $key, $default = null)
{
if (is_null($key)) {
return $target;
}
$key = is_array($key) ? $key : explode('.', $key);
while (! is_null($segment = array_shift($key))) {
if ($segment === '*') {
if ($target instanceof Collection) {
$target = $target->all();
} elseif (! is_array($target)) {
return value($default);
}
$result = [];
foreach ($target as $item) {
$result[] = data_get($item, $key);
}
return in_array('*', $key) ? Arr::collapse($result) : $result;
}
if (Arr::accessible($target) && Arr::exists($target, $segment)) {
$target = $target[$segment];
} elseif (is_object($target) && isset($target->{$segment})) {
$target = $target->{$segment};
} else {
return value($default);
}
}
return $target;
}
}

————————————————
原文作者:Ίκαρος
转自链接:https://learnku.com/articles/18107

Laravel 避免 Trying to get property of non-object 错误的六种方法 [新增第六种 data_get]的更多相关文章

  1. [转载][jQuery] Cannot read property ‘msie’ of undefined错误的解决方法

    参考 [jQuery] Cannot read property ‘msie’ of undefined错误的解决方法 ---------------------------------------- ...

  2. [jQuery1.9]Cannot read property ‘msie’ of undefined错误的解决方法

    原文:[jQuery1.9]Cannot read property 'msie' of undefined错误的解决方法 $.browser在jQuery1.9里被删除了,所以项目的js代码里用到$ ...

  3. [jQuery] Cannot read property ‘msie’ of undefined错误的解决方法 --转

    初用Yii的srbac模块.出现 Cannot read property ‘msie’ of undefined 错误.上网查询,找到如下的文章.使用文末的打补丁的方法,成功搞定.感谢. ===== ...

  4. [jQuery] Cannot read property ‘msie’ of undefined错误的解决方法

    最近把一个项目的jQuery升级到最新版,发现有些页面报错Cannot read property ‘msie’ of undefined.上jQuery网站上搜了一下,原因是$.browser这个a ...

  5. jquery升级到新版本报错[jQuery] Cannot read property ‘msie’ of undefined错误的解决方法(转)

    最近把一个项目的jQuery升级到最新版,发现有些页面报错Cannot read property 'msie' of undefined.上jQuery网站上搜了一下,原因是$.browser这个a ...

  6. 2.mongoDB add user in v3.0 问题的解决(Property 'addUser' of object admin is not a func)

    问题:创建mongodb帐户时,出错 > db.addUser('jyu', 'aerohive')  2015-08-05T20:03:02.767+0800 E QUERY    TypeE ...

  7. Vue的报错:Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>'

    Vue的报错:Uncaught TypeError: Cannot assign to read only property 'exports' of object '#<Object>' ...

  8. Vue报错:Uncaught TypeError: Cannot assign to read only property’exports‘ of object’#<Object>‘的解决方法

    发现问题 运行一下以前的一个Vue+webpack的 vue仿新闻网站  小项目,报错 由于自己vue学习不深入,老是这个报错,找了好久(确切的说是整整一下午^...^)才找到原因 -v- Uncau ...

  9. [one day one question] webpack 打包报错 Cannot assign to read only property 'exports' of object '#<Object>'

    问题描述: webpack 打包报错 Cannot assign to read only property 'exports' of object '#<Object>',这怎么破? 解 ...

随机推荐

  1. Lucas(卢卡斯)定理

    公式 $$C_n^m\%p=C_{n/p}^{m/p}*C_{n\%p}^{m\%p}\%p~~(p为素数)$$ 代码如下 typedef long long ll; ll mod_pow(ll x, ...

  2. MySQL中EXPLAIN命令详细解析

    很多情况下我们需要知道某条SQL语句的性能,都会通过EXPLAIN命令来查看查询优化器是如何执行的. 如何使用 使用EXPLAIN很简单,只需要在执行的SQL前面加上EXPLAIN即可 explain ...

  3. Pytorch_第六篇_深度学习 (DeepLearning) 基础 [2]---神经网络常用的损失函数

    深度学习 (DeepLearning) 基础 [2]---神经网络常用的损失函数 Introduce 在上一篇"深度学习 (DeepLearning) 基础 [1]---监督学习和无监督学习 ...

  4. Java 基础 —— 注解 Annotation

    简介 Annotation 是从 JDK 5.0 引入的. 注解使得我们可以以编译器验证的格式存储程序的额外信息.注解可以生成描述符文件,甚至是新的类定义,并且有助于减轻编写"样板" ...

  5. C++ 对象的初始化

    目录 默认初始化 默认构造函数(default constructor) 构造函数初始值列表(cosntructor initializer list) 直接初始化和拷贝初始化 拷贝构造函数(copy ...

  6. C#设计模式之21-策略模式

    策略模式(Stragety Pattern) 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/427 访问. 策略模式属于 ...

  7. C#LeetCode刷题之#674-最长连续递增序列( Longest Continuous Increasing Subsequence)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3734 访问. 给定一个未经排序的整数数组,找到最长且连续的的递增 ...

  8. C#开发笔记之07-如何实现交换2个变量的值而不引入中间变量?

    C#开发笔记概述 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/963 访问. 这里给出常见的7种方法,仅供大家参考,部 ...

  9. unity3d学习笔记(一) 第一人称视角实现和倒计时实现

    unity3d学习笔记(一) 第一人称视角实现和倒计时实现 1. 第一人称视角 (1)让mainCamera和player(视角对象)同步在一起 因为我们的player是生成的,所以不能把mainCa ...

  10. 怎么写简历,简历才不会被丢到非洲&#127757;

    前言 只有光头才能变强. 文本已收录至我的GitHub精选文章,欢迎Star:https://github.com/ZhongFuCheng3y/3y 最近的三歪朋友圈可以看到很多的字节.腾讯的同学都 ...