Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[13.x] Fix Eloquent Builder instance in relation class inside closure #53551

Draft
wants to merge 6 commits into
base: master
Choose a base branch
from
35 changes: 34 additions & 1 deletion src/Illuminate/Database/Eloquent/Relations/Relation.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\MultipleRecordsFoundException;
use Illuminate\Database\Query\Expression;
use Illuminate\Support\Traits\Conditionable;
use Illuminate\Support\Collection as BaseCollection;

use Illuminate\Support\Traits\ForwardsCalls;
use Illuminate\Support\Traits\Macroable;

Expand All @@ -23,7 +25,7 @@
*/
abstract class Relation implements BuilderContract
{
use ForwardsCalls, Macroable {
use ForwardsCalls, Conditionable, Macroable {
Macroable::__call as macroCall;
}

Expand Down Expand Up @@ -121,6 +123,37 @@ public static function noConstraints(Closure $callback)
}
}

/**
* Conditionally modify the relation.
*
* Unlike the query builder's when method, we always return the relation
* instance so that relationship-specific methods remain available.
*/
public function when($value, callable $callback, callable $default = null)
{
if ($this instanceof BelongsToMany) {
// For BelongsToMany, run the callback on the relation instance.
if ($value) {
$callback($this, $value);
} elseif ($default) {
$default($this, $value);
}
return $this;
}

if ($this instanceof MorphTo) {
// For MorphTo, update the underlying query builder and set it back on the relation.
$query = $this->getQuery()->when($value, $callback, $default);
$this->setQuery($query);
return $this;
}

// For all other relation types, update the underlying query builder.
$query = $this->getQuery()->when($value, $callback, $default);
$this->setQuery($query);
return $this;
}

/**
* Set the base constraints on the relation query.
*
Expand Down
3 changes: 2 additions & 1 deletion src/Illuminate/Database/Query/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use Illuminate\Support\Collection;
use Illuminate\Support\LazyCollection;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Conditionable;
use Illuminate\Support\Traits\ForwardsCalls;
use Illuminate\Support\Traits\Macroable;
use InvalidArgumentException;
Expand All @@ -34,7 +35,7 @@
class Builder implements BuilderContract
{
/** @use \Illuminate\Database\Concerns\BuildsQueries<object> */
use BuildsQueries, ExplainsQueries, ForwardsCalls, Macroable {
use BuildsQueries, ExplainsQueries, ForwardsCalls, Conditionable, Macroable {
__call as macroCall;
}

Expand Down
54 changes: 54 additions & 0 deletions tests/Integration/Database/EloquentModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

namespace Illuminate\Tests\Integration\Database;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Schema;
Expand All @@ -22,6 +24,13 @@ protected function afterRefreshingDatabase()
$table->string('name');
$table->string('title');
});

Schema::create('test_model1_test_model2', function (Blueprint $table) {
$table->increments('id');
$table->integer('test_model1_id');
$table->integer('test_model2_id');
$table->timestamp('updated_at')->nullable();
});
}

public function testUserCanUpdateNullableDate()
Expand Down Expand Up @@ -126,6 +135,45 @@ public function testInsertRecordWithReservedWordFieldName()
'analyze' => true,
]);
}

public function testBelongsToManyWhenMethodMaintainsRelationInstance()
{
$model1 = TestModel1::create(['nullable_date' => now()]);
$model2 = TestModel2::create([
'name' => 'Test Name',
'title' => 'Test Title',
]);

// Create the pivot record
$model1->testRelation1()->attach($model2->id, [
'updated_at' => '2023-01-01 00:00:00',
]);

$query = $model1->testRelation1()
->when(true, function ($query) {
$this->assertInstanceOf(
BelongsToMany::class,
$query,
'Query should be instance of BelongsToMany within when callback'
);

return $query->wherePivotBetween(
'updated_at',
['2022-01-01 00:00:00', '2024-01-01 00:00:00']
);
});

$this->assertInstanceOf(
BelongsToMany::class,
$query,
'Query should remain instance of BelongsToMany after when method'
);

$result = $query->get();

$this->assertInstanceOf(Collection::class, $result);
$this->assertCount(1, $result);
}
}

class TestModel1 extends Model
Expand All @@ -134,6 +182,12 @@ class TestModel1 extends Model
public $timestamps = false;
protected $guarded = [];
protected $casts = ['nullable_date' => 'datetime'];

public function testRelation1()
{
return $this->belongsToMany(TestModel2::class)
->withPivot('updated_at');
}
}

class TestModel2 extends Model
Expand Down