Skip to content

Commit

Permalink
Allow key arguments to model getAttributes (#15722)
Browse files Browse the repository at this point in the history
  • Loading branch information
ntzm authored and taylorotwell committed Oct 3, 2016
1 parent 769ccae commit 52e56cd
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
24 changes: 21 additions & 3 deletions src/Illuminate/Database/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -3067,13 +3067,31 @@ public function is(Model $model)
}

/**
* Get all of the current attributes on the model.
* Get a selection of the current attributes on the model.
*
* @param array $keys
*
* @return array
*/
public function getAttributes()
public function getAttributes($keys = [])
{
return $this->attributes;
if ($keys === []) {
return $this->attributes;
}

$keys = is_array($keys) ? $keys : func_get_args();

$result = [];

foreach ($keys as $key) {
$value = $this->getAttribute($key);

if (! is_null($value)) {
$result[$key] = $value;
}
}

return $result;
}

/**
Expand Down
12 changes: 12 additions & 0 deletions tests/Database/DatabaseEloquentModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,18 @@ public function testAttributeManipulation()
$this->assertEquals(json_encode(['name' => 'taylor']), $attributes['list_items']);
}

public function testGetMultipleAttributes()
{
$model = new EloquentModelStub(['name' => 'taylor', 'framework' => 'laravel', 'foo' => 'bar']);

$this->assertEquals(['name' => 'taylor', 'foo' => 'bar'], $model->getAttributes('name', 'foo'));
$this->assertEquals(['name' => 'taylor', 'foo' => 'bar'], $model->getAttributes(['name', 'foo']));
$this->assertEquals(['name' => 'taylor'], $model->getAttributes('name'));
$this->assertEquals(['name' => 'taylor'], $model->getAttributes(['name']));

$this->assertEquals(['name' => 'taylor'], $model->getAttributes(['name', 'doesntexist']));
}

public function testDirtyAttributes()
{
$model = new EloquentModelStub(['foo' => '1', 'bar' => 2, 'baz' => 3]);
Expand Down

0 comments on commit 52e56cd

Please sign in to comment.