Reputation: 9047
I'm trying to add an custom attribute unto the retrieved collection
$category = categories::where('cat_id',$id)->first();
foreach($category as $c):
dd(var_dump($c->cat_id))
$c->custom_attr = $c->cat_id;
endforeach;
but it throws me this error
Trying to get property of non-object
not unless if I use 'get()' instead of 'first()' then it worked. If I do
$category = categories::where('cat_id',$id)->first();
foreach($category as $c):
dd(var_dump($c))
endforeach;
it returns me
bool(true)
null
if I do
$category = categories::where('cat_id',$id)->first();
foreach($category as $c):
dd(var_dump('xx'))
endforeach;
Sure the dump returns 'xx'. Any ideas, help please?
Upvotes: 1
Views: 536
Reputation: 163978
You should use get()
instead of first()
.
first()
gives you an object, get()
will give you a collection of objects.
If you want to get properties, do not use foreach()
or for()
, just get properties like this:
$category->name;
Upvotes: 4