diff --git a/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php b/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php index 5bcb9b9ad94b..0bdf4fad0f21 100755 --- a/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php +++ b/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php @@ -749,6 +749,22 @@ public function each(callable $callback, $count = 1000) }); } + /** + * Get a lazy collection for the given query. + * + * @return \Illuminate\Support\LazyCollection + */ + public function cursor() + { + $this->query->addSelect($this->shouldSelect()); + + return $this->query->cursor()->map(function ($model) { + $this->hydratePivotRelation([$model]); + + return $model; + }); + } + /** * Hydrate the pivot table relationship on the models. * diff --git a/tests/Database/DatabaseEloquentIntegrationTest.php b/tests/Database/DatabaseEloquentIntegrationTest.php index f1b16898affc..ac39258cb30a 100644 --- a/tests/Database/DatabaseEloquentIntegrationTest.php +++ b/tests/Database/DatabaseEloquentIntegrationTest.php @@ -767,6 +767,18 @@ public function testBelongsToManyRelationshipModelsAreProperlyHydratedOverEachRe }); } + public function testBelongsToManyRelationshipModelsAreProperlyHydratedOverCursorRequest() + { + $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']); + $friend = $user->friends()->create(['email' => 'abigailotwell@gmail.com']); + + foreach (EloquentTestUser::first()->friends()->cursor() as $result) { + $this->assertSame('abigailotwell@gmail.com', $result->email); + $this->assertEquals($user->id, $result->pivot->user_id); + $this->assertEquals($friend->id, $result->pivot->friend_id); + } + } + public function testBasicHasManyEagerLoading() { $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);