Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 3 commits into from
Jan 9, 2023

Conversation

jessarcher
Copy link
Member

@jessarcher jessarcher commented Jan 9, 2023

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' => '[email protected]'
    ]
]
*/

// 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.

src/Illuminate/Database/Eloquent/Collection.php Outdated Show resolved Hide resolved
src/Illuminate/Database/Eloquent/Collection.php Outdated Show resolved Hide resolved
@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