From d4f08a4e18d6e470a8d9adeb52d7235cff0d19af Mon Sep 17 00:00:00 2001 From: Jordan Pittman Date: Tue, 31 Jan 2017 21:34:42 -0500 Subject: [PATCH 1/2] Make relation macroable --- src/Illuminate/Database/Eloquent/Relations/Relation.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/Illuminate/Database/Eloquent/Relations/Relation.php b/src/Illuminate/Database/Eloquent/Relations/Relation.php index 18f3de1cb8e6..de4cf639b764 100755 --- a/src/Illuminate/Database/Eloquent/Relations/Relation.php +++ b/src/Illuminate/Database/Eloquent/Relations/Relation.php @@ -5,12 +5,17 @@ use Closure; use Illuminate\Support\Arr; use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Traits\Macroable; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Query\Expression; use Illuminate\Database\Eloquent\Collection; abstract class Relation { + use Macroable { + __call as macroCall; + } + /** * The Eloquent query builder instance. * @@ -328,6 +333,10 @@ protected static function buildMorphMapFromModels(array $models = null) */ public function __call($method, $parameters) { + if (static::hasMacro($method)) { + return $this->macroCall($method, $parameters); + } + $result = call_user_func_array([$this->query, $method], $parameters); if ($result === $this->query) { From 0f44bf1d55c00b046536d766fe782907445d5fa0 Mon Sep 17 00:00:00 2001 From: Jordan Pittman Date: Tue, 31 Jan 2017 21:42:40 -0500 Subject: [PATCH 2/2] Add test for macroable relations --- tests/Database/DatabaseEloquentRelationTest.php | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tests/Database/DatabaseEloquentRelationTest.php b/tests/Database/DatabaseEloquentRelationTest.php index 3b85cfc16e97..395cd1d287b5 100755 --- a/tests/Database/DatabaseEloquentRelationTest.php +++ b/tests/Database/DatabaseEloquentRelationTest.php @@ -64,6 +64,19 @@ public function testSettingMorphMapWithNumericKeys() Relation::morphMap([], false); } + + public function testMacroable() + { + Relation::macro('foo', function () { + return 'foo'; + }); + + $model = new EloquentRelationResetModelStub(); + $relation = new EloquentRelationStub($model->newQuery(), $model); + + $result = $relation->foo(); + $this->assertEquals('foo', $result); + } } class EloquentRelationResetModelStub extends Model