我有一个有几个字段的模型,包括两个存储JSON字典列表的文本字段。其中一个用于存储图像数据,运行良好;然而,当我试图从刀片模板访问该属性时,第二个存储具有链接的字典列表的返回Undefined property: stdClass::$title
。
如果我删除对我的links属性的调用,所有其他属性(包括JSON转换为对象数组的图像)都呈现良好。
我已经尝试dd()
的链接属性,它都显示它的设置,它是一个数组,它充满了对象的属性(标题,url),我试图访问失败时。
一旦我尝试实际访问它们,然而,我得到Undefined property
的确切属性,我试图访问。
想知道是否有人遇到过这样的事情?真正奇怪的是,图像JSON数据的呈现没有任何问题。所有这些都与路由模型绑定绑定在一起,这被验证是有效的。
Eloquent Model中的属性getter
public function getLinksAttribute() {
if (!empty($this->attributes['links'])) {
return json_decode($this->attributes['links']);
}
}
public function getImagesAttribute() {
if (!empty($this->attributes['images'])) {
return json_decode($this->attributes['images']);
}
}
叶片模板中调用link属性的部分,失败
@if (is_array($artist->links))
<div class="links">
<h4>Links</h4>
<ul>
@foreach ($artist->links as $link)
{{ $link->title }}, {{ $link->url }}
@endforeach
</ul>
</div>
@endif
叶片模板调用images属性的部分,成功
@if (is_array($artist->images))
<ul class="images">
@foreach ($artist->images as $image)
<li>{!! Html::image(Html::buildS3Url(array(
"basedir" => "artists", "id" => $artist->id, "prefix" => $image->prefix,
"extension" => $image->extension, "conversion" => "display")
), $artist->name) !!}</li>
@endforeach
</ul>
@endif
Json通过tinker对数据库中的数据进行编码,随后dd()
### links (doesn't work)
#tinker output
links: "[{"'title'":"test","'url'":"http:'/'/test.com"}]",,
# dd()
array:1 [▼
0 => {#308 ▼
+"'title'": "test"
+"'url'": "http://test.com"
}
]
### images (works)
# tinker output
images: "[{"prefix":1440693993,"extension":"png"},{"prefix":1440697822,"extension":"png"}]"
# dd()
array:2 [▼
0 => {#308 ▼
+"prefix": 1440693993
+"extension": "png"
}
1 => {#307 ▼
+"prefix": 1440697822
+"extension": "png"
}
]
"未定义属性:stdClass::$title"
似乎在你的一个链接缺少标题属性
你可以通过:
@foreach ($artist->links as $link)
<?php if(property_exists($link, "title")) : ?>
{{ $link->title }}
<?php else : ?>
NO TITLE [DEBUG: {{ dd($link) }}]
<?php endif; ?>, {{ $link->url }}
@endforeach
我还发现了一件事:
links: "[{"'title'":"test","'url'":"http:'/'/test.com"}]",,
你的元素字段是' title ' (with '),但它必须是"title": "test"