[英]Laravel - Cannot Access Collection Indexes
For sure it's an understanding issue on my part. 当然,这是我的理解问题。 I'm just trying to create a collection in which the elements can be output. 我只是试图创建一个可以在其中输出元素的集合。
Example: 例:
So I want to be able to execute: 所以我希望能够执行:
$collection=collect([
'index1' => 'data1',
'index2' => 'data2',
'index3' => 'data3',
]);
$row=$collection->first();
dd($row->index1);
Or similar.. But I get the error 或类似..但我得到了错误
trying to get property of a non object. 试图获取非对象的属性。
It's an understanding issue about Laravel collections, I've read the Laravel documentation which goes from basic usage, to API reference. 这是关于Laravel集合的理解问题,我已经阅读了Laravel文档,从基本用法到API参考。 I cannot find the information on how to produce this basic static collection. 我找不到有关如何生成此基本静态集合的信息。
Can someone help? 有人可以帮忙吗?
$row=$collection->first();
points to the value data1
, not an object/array. 指向值data1
,而不是对象/数组。
To get the expected behavior try the code below, it wraps each in individual arrays. 要获得预期的行为,请尝试以下代码,它将每个代码包装在单独的数组中。
$collection=collect([
['index1' => 'data1'],
['index2' => 'data2'],
['index3' => 'data3'],
]);
$row=$collection->first();
dd($row->index1);
As Laravel collections implement ArrayAccess
you can simply access collection items as you do with an array 当Laravel集合实现ArrayAccess
您可以像访问数组一样简单地访问集合项
$value = $collection['index1'];
or you can use the get
method on collections 或者您可以在集合上使用get
方法
$value = $collection->get('index1');
Thanks for your answers, I see the $collection['index1']; 感谢您的回答,我看到了$ collection ['index1']; format works. 格式有效。
It's not exactly what I wanted, let me explain why. 这不完全是我想要的,让我解释一下原因。 I know there's probably a better way of doing it although, for the sake of this particular coding requirement I'd like to know the answer to this. 我知道这样做可能有更好的方法,但是出于特定的编码要求,我想知道答案。
I'm building a CRUD blade form. 我正在建立一个CRUD刀片表单。
On my blade I'll have 'field1' with initial output of $dbcollection->field1 在我的刀片上,我将拥有'field1',其初始输出为$ dbcollection-> field1
Now of course if the database returns a null (create required) this output will fail. 当然,现在如果数据库返回空值(需要创建),则此输出将失败。 So what I'm trying to do here is pass blade a NULL-filled collection it understands so at least it doesn't complain about non instance of an object and avoiding @if statements on the blade form to account for differences in coding format. 因此,我在这里要做的是将其理解为NULL的集合传递给刀片服务器,这样至少它不会抱怨对象的非实例,并且避免在刀片服务器窗体上使用@if语句来解释编码格式的差异。
I believe this is what you are looking for: 我相信这是您要寻找的:
Controller
: Controller
:
$collection=collect([
'index1' => 'data1',
'index2' => 'data2',
'index3' => 'data3',
]);
$row = $collection->first();
view
: view
:
<input type="text" value="{{ ($row->index1 ? $row->index1 : '') }}" >
.
.
.
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.