Laravel Blade模板尝试获取非对象的属性时如何返回null而不是ErrorException [英] Laravel Blade template how to return null instead of ErrorException when trying to get property of non-object

查看:96
本文介绍了Laravel Blade模板尝试获取非对象的属性时如何返回null而不是ErrorException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些Laravel Blade模板,并且我的模型可能包含空对象.我非常想尝试获取对象属性,如果有错误,则返回null.

I'm writing some Laravel Blade templates, and I have models that may have null objects. I would very much like to just try and get the object property and if there is an error, just return null.

所以不必写这个:

@if ($model->child_object_that_may_be_null)
    {{ $model->child_object_that_may_be_null->interesting_property }}
@endif

我可以这样写:

{{ $model->child_object_that_may_be_null->interesting_property }}

,如果子对象为null,则结果为null.

and if the child object is null, then the result evaluates to null.

我只想使用刀片模板来执行此操作,而不是应用程序中的所有位置(例如,我仍然想在控制器中获取错误).

I want to only do this with my blade templates, and not everywhere in the application (I'd still like to get the error in the controllers for example).

有没有简单的方法可以做到这一点?我也确实不想每次都在刀片模板中尝试/捕获异常.

Is there an easy way to accomplish this? I also really don't want to have to try/catch the exception each time in the blade templates either.

基本上,当我不在乎我的孩子为null时,我试图使刀片模板的编写更容易/更简短,如果它为null,则对于渲染部分,不存在的属性也应该仅为null

Basically, I'm trying to make the blade templates easier/shorter to write when I don't care that I child is null, if it is null then its non-existent property should just be null also for the rendering portion.

推荐答案

您可以使用

You can use array_get as:

{{ array_get($model, 'child_object_that_may_be_null.interesting_property') }}

array_get函数使用点"符号从深度嵌套的数组中检索值.

The array_get function retrieves a value from a deeply nested array using "dot" notation.

注意-它只能与Laravel的模型对象一起使用

这篇关于Laravel Blade模板尝试获取非对象的属性时如何返回null而不是ErrorException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆