Skip to content

Commit c05334d

Browse files
authored
Eloquent\Builder::with() support for closures (#32924)
1 parent e4297f0 commit c05334d

File tree

2 files changed

+18
-3
lines changed

2 files changed

+18
-3
lines changed

src/Illuminate/Database/Eloquent/Builder.php

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1075,12 +1075,17 @@ protected function createNestedWhere($whereSlice, $boolean = 'and')
10751075
/**
10761076
* Set the relationships that should be eager loaded.
10771077
*
1078-
* @param mixed $relations
1078+
* @param string|array $relations
1079+
* @param string|\Closure|null $callback
10791080
* @return $this
10801081
*/
1081-
public function with($relations)
1082+
public function with($relations, $callback = null)
10821083
{
1083-
$eagerLoad = $this->parseWithRelations(is_string($relations) ? func_get_args() : $relations);
1084+
if ($callback instanceof Closure) {
1085+
$eagerLoad = $this->parseWithRelations([$relations => $callback]);
1086+
} else {
1087+
$eagerLoad = $this->parseWithRelations(is_string($relations) ? func_get_args() : $relations);
1088+
}
10841089

10851090
$this->eagerLoad = array_merge($this->eagerLoad, $eagerLoad);
10861091

tests/Database/DatabaseEloquentBuilderTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -607,6 +607,16 @@ public function testEagerLoadParsingSetsProperRelationships()
607607
$this->assertInstanceOf(Closure::class, $eagers['orders']);
608608
$this->assertNull($eagers['orders']());
609609
$this->assertSame('foo', $eagers['orders.lines']());
610+
611+
$builder = $this->getBuilder();
612+
$builder->with('orders.lines', function () {
613+
return 'foo';
614+
});
615+
$eagers = $builder->getEagerLoads();
616+
617+
$this->assertInstanceOf(Closure::class, $eagers['orders']);
618+
$this->assertNull($eagers['orders']());
619+
$this->assertSame('foo', $eagers['orders.lines']());
610620
}
611621

612622
public function testQueryPassThru()

0 commit comments

Comments
 (0)