I create a collection for list of all address of a particular user and call it as:
$addresses = collect($user->GetAddress);
$addresses = $addresses->where('deleted', 0);
$addresses = $addresses->except(['deleted', 'created_at', 'updated_at']);
I get the output like:
[
{
"id": 1,
"user_id": 1,
"name": "mr.test",
"line1": "test1",
"line2": "test2",
"pincode": 100,
"city": "test3",
"state": "test4",
"mobile": "test5",
"default": 0,
"deleted": 0,
"created_at": "2017-02-23 09:20:09",
"updated_at": "2017-02-23 09:20:09"
}
]
It still returns the fields that I do an except on. What am I doing wrong?
I even tried these:
$addresses = $addresses->each(function ($item, $key) {
return $item->except(['deleted', 'created_at', 'updated_at']);
});
and
$addresses = $addresses->each->except(['deleted', 'created_at', 'updated_at']);
except
only works when you have a single array with keys, not for a nested array. Your solution with the each function should work, but I think you have to cast $item
to a collection first.
Like so:
$addresses = $addresses->map(function ($item, $key) {
return collect($item)->except(['deleted', 'created_at', 'updated_at'])->toArray();
});
The except
method works on the outer array/collection i.e. on the keys of the collection. So you'd have to use an each
operator
The code below does not work because the $item
is not a collection, but a model.
$addresses = $addresses->each(function ($item, $key) {
return $item->except(['deleted', 'created_at', 'updated_at']);
});
One solution to your problem would be to use the select
method like this (provided GetAddresses is a real laravel relationship).
$user->GetAddresses()->select(['col1', 'col2'])->get()
Another would be to map your output like so:
$addresses = $addresses->map(function ($item, $key) {
return [
"id": $item->id,
"user_id": $item->user_id,
"name": $item->name,
"line1": $item->line1,
// etc...
];
});
Yet another solution would be to utilize the $hidden
attribute (see this link) on the model and use to to toArray()
on each item. That would hide the attributes you have entered in the $hidden
instance variable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With