Skip to content

[9.x] Add setVisible and setHidden to Eloquent Collection - #45558

Merged
taylorotwell merged 3 commits into
9.xfrom
eloquent-collection-set-visible-hidden
Jan 9, 2023
Merged

[9.x] Add setVisible and setHidden to Eloquent Collection#45558
taylorotwell merged 3 commits into
9.xfrom
eloquent-collection-set-visible-hidden

Conversation

@jessarcher

@jessarcher jessarcher commented Jan 9, 2023

Copy link
Copy Markdown
Member

This PR adds setVisible and setHidden methods to Eloquent Collections.

We already have the makeVisible and makeHidden methods, but makeVisible is only useful when a property is usually hidden or when the model has a non-empty $visible property, and makeHidden is only useful when you want to be explicit about what is excluded, not what is included.

Example:

I want to return an array of users with just the ID and name, hiding other attributes such as email and any future attributes that may be added.

// This is effectively a no-op because these fields are not typically hidden.
$users->makeVisible(['id', 'name'])->toArray(); ❌
/*
[
    [
        'id' => 1,
        'name' => 'Test User',
        'email' => 'test@example.com'
    ]
]
*/

// This only gives us the desired result until a new non-hidden attribute is added to the model.
$users->makeHidden(['email'])->toArray(); 😐️
/*
[
    [
        'id' => 1,
        'name' => 'Test User',
    ]
]
*/

// This allows us to be explicit about the data we want, and it won't leak as new attributes are added to the model.
$users->setVisible(['id', 'name'])->toArray(); ✅
/*
[
    [
        'id' => 1,
        'name' => 'Test User',
    ]
]
*/

This is especially useful when passing collections to Inertia.

Comment thread src/Illuminate/Database/Eloquent/Collection.php Outdated
Comment thread src/Illuminate/Database/Eloquent/Collection.php Outdated
taylorotwell and others added 2 commits January 9, 2023 09:58
Co-authored-by: Nuno Maduro <enunomaduro@gmail.com>
Co-authored-by: Nuno Maduro <enunomaduro@gmail.com>
@taylorotwell
taylorotwell merged commit a656303 into 9.x Jan 9, 2023
@taylorotwell
taylorotwell deleted the eloquent-collection-set-visible-hidden branch January 9, 2023 15:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants