Skip to content

[12.x] Added except() method to Model class for excluding attributes #55072

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

Merged
merged 5 commits into from
Mar 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -2007,6 +2007,27 @@ public function only($attributes)
return $results;
}

/**
* Get all attributes except the given ones.
*
* @param array|mixed $attributes
* @return array
*/
public function except($attributes)
{
$attributes = is_array($attributes) ? $attributes : func_get_args();

$results = [];

foreach ($this->getAttributes() as $key => $value) {
if (! in_array($key, $attributes)) {
$results[$key] = $value;
}
}

return $results;
}

/**
* Sync the original attributes with the current.
*
Expand Down
12 changes: 12 additions & 0 deletions tests/Database/DatabaseEloquentModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,18 @@ public function testOnly()
$this->assertEquals(['first_name' => 'taylor', 'last_name' => 'otwell'], $model->only(['first_name', 'last_name']));
}

public function testExcept()
{
$model = new EloquentModelStub;
$model->first_name = 'taylor';
$model->last_name = 'otwell';
$model->project = 'laravel';

$this->assertEquals(['first_name' => 'taylor', 'last_name' => 'otwell'], $model->except('project'));
$this->assertEquals(['project' => 'laravel'], $model->except('first_name', 'last_name'));
$this->assertEquals(['project' => 'laravel'], $model->except(['first_name', 'last_name']));
}

public function testNewInstanceReturnsNewInstanceWithAttributesSet()
{
$model = new EloquentModelStub;
Expand Down
Loading