Reputation: 177
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. I cannot find the information on how to produce this basic static collection.
Can someone help?
Upvotes: 0
Views: 1129
Reputation: 1203
I believe this is what you are looking for:
Controller
:
$collection=collect([
'index1' => 'data1',
'index2' => 'data2',
'index3' => 'data3',
]);
$row = $collection->first();
view
:
<input type="text" value="{{ ($row->index1 ? $row->index1 : '') }}" >
.
.
.
.
Upvotes: 0
Reputation: 177
Thanks for your answers, I see the $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.
On my blade I'll have 'field1' with initial output of $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.
Upvotes: 0
Reputation: 5124
As Laravel collections implement ArrayAccess
you can simply access collection items as you do with an array
$value = $collection['index1'];
or you can use the get
method on collections
$value = $collection->get('index1');
Upvotes: 0
Reputation: 2435
$row=$collection->first();
points to the value data1
, not an object/array.
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);
Upvotes: 1