Commit e3ff8801 authored by Jens Segers's avatar Jens Segers

Allow dot notition for getAttribute

parent 57722d23
...@@ -195,6 +195,52 @@ abstract class Model extends \Jenssegers\Eloquent\Model { ...@@ -195,6 +195,52 @@ abstract class Model extends \Jenssegers\Eloquent\Model {
return parent::getTable(); return parent::getTable();
} }
/**
* Get an attribute from the model.
*
* @param string $key
* @return mixed
*/
public function getAttribute($key)
{
// Check if the key is an array dot notation.
if (strstr($key, '.'))
{
$attributes = array_dot($this->attributes);
if (array_key_exists($key, $attributes))
{
return $this->getAttributeValue($key);
}
}
return parent::getAttribute($key);
}
/**
* Get an attribute from the $attributes array.
*
* @param string $key
* @return mixed
*/
protected function getAttributeFromArray($key)
{
if (array_key_exists($key, $this->attributes))
{
return $this->attributes[$key];
}
else if (strstr($key, '.'))
{
$attributes = array_dot($this->attributes);
if (array_key_exists($key, $attributes))
{
return $attributes[$key];
}
}
}
/** /**
* Set a given attribute on the model. * Set a given attribute on the model.
* *
......
...@@ -419,4 +419,19 @@ class ModelTest extends TestCase { ...@@ -419,4 +419,19 @@ class ModelTest extends TestCase {
$this->assertTrue(is_array($result)); $this->assertTrue(is_array($result));
} }
public function testDotNotation()
{
$user = User::create(array(
'name' => 'John Doe',
'address' => [
'city' => 'Paris',
'country' => 'France',
]
));
$this->assertEquals('Paris', $user->getAttribute('address.city'));
$this->assertEquals('Paris', $user['address.city']);
$this->assertEquals('Paris', $user->{'address.city'});
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment