Skip to content

Commit 3a46721

Browse files
committed
Even more fluent eloquent model via magic setters
Now it is possible to use Eloquent's magic setters in chains. For example: $model->set_foo('foo')->take(10)->set_bar(some_function()); // ...even though setters 'foo' and 'bar' are not defined on the model
1 parent cffded6 commit 3a46721

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

laravel/database/eloquent/model.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -770,6 +770,7 @@ public function __call($method, $parameters)
770770
elseif (starts_with($method, 'set_'))
771771
{
772772
$this->set_attribute(substr($method, 4), $parameters[0]);
773+
return $this;
773774
}
774775

775776
// Finally we will assume that the method is actually the beginning of a

laravel/tests/cases/eloquent.test.php

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,19 @@ public function testAttributeMagicSetterMethodChangesAttribute()
133133
Model::$accessible = null;
134134
}
135135

136+
/**
137+
* Test the Model::__set method allows chaining.
138+
*
139+
* @group laravel
140+
*/
141+
public function testAttributeMagicSetterMethodAllowsChaining()
142+
{
143+
$model = new Model;
144+
$this->assertInstanceOf('Model', $model->set_foo('foo'));
145+
$model->set_bar('bar')->set_baz('baz');
146+
$this->assertEquals(array('foo' => 'foo', 'bar' => 'bar', 'baz' => 'baz'), $model->to_array());
147+
}
148+
136149
/**
137150
* Test the Model::__get method.
138151
*
@@ -288,4 +301,4 @@ public function testConvertingToArray()
288301

289302
}
290303

291-
}
304+
}

0 commit comments

Comments
 (0)