Skip to content

Commit 0026d3b

Browse files
authored
[12.x] Added except() method to Model class for excluding attributes (#55072)
* Added except() method to Model class for excluding attributes * Refactor code * Refactor code * Code formatting
1 parent 40373f9 commit 0026d3b

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2007,6 +2007,27 @@ public function only($attributes)
20072007
return $results;
20082008
}
20092009

2010+
/**
2011+
* Get all attributes except the given ones.
2012+
*
2013+
* @param array|mixed $attributes
2014+
* @return array
2015+
*/
2016+
public function except($attributes)
2017+
{
2018+
$attributes = is_array($attributes) ? $attributes : func_get_args();
2019+
2020+
$results = [];
2021+
2022+
foreach ($this->getAttributes() as $key => $value) {
2023+
if (! in_array($key, $attributes)) {
2024+
$results[$key] = $value;
2025+
}
2026+
}
2027+
2028+
return $results;
2029+
}
2030+
20102031
/**
20112032
* Sync the original attributes with the current.
20122033
*

tests/Database/DatabaseEloquentModelTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -605,6 +605,18 @@ public function testOnly()
605605
$this->assertEquals(['first_name' => 'taylor', 'last_name' => 'otwell'], $model->only(['first_name', 'last_name']));
606606
}
607607

608+
public function testExcept()
609+
{
610+
$model = new EloquentModelStub;
611+
$model->first_name = 'taylor';
612+
$model->last_name = 'otwell';
613+
$model->project = 'laravel';
614+
615+
$this->assertEquals(['first_name' => 'taylor', 'last_name' => 'otwell'], $model->except('project'));
616+
$this->assertEquals(['project' => 'laravel'], $model->except('first_name', 'last_name'));
617+
$this->assertEquals(['project' => 'laravel'], $model->except(['first_name', 'last_name']));
618+
}
619+
608620
public function testNewInstanceReturnsNewInstanceWithAttributesSet()
609621
{
610622
$model = new EloquentModelStub;

0 commit comments

Comments
 (0)