Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Collections except not working as expected

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']);
like image 417
JackSlayer94 Avatar asked Feb 24 '17 07:02

JackSlayer94


2 Answers

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();
});
like image 156
Jerodev Avatar answered Nov 13 '22 12:11

Jerodev


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']);
});

Solution 1

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()

Solution 2

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...
    ];
});

Solution 3

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

like image 34
KimWordWax Avatar answered Nov 13 '22 14:11

KimWordWax