framework
framework copied to clipboard
[12.x] Fix Eloquent Builder instance in relation class inside closure
Fixes #53292
Description
When using the when() method on a BelongsToMany relationship, the query builder instance was being returned instead of the relationship instance, preventing the use of relationship-specific methods like wherePivot.
This PR fixes the issue by maintaining the relationship instance within the when() method specifically for BelongsToMany relationships while preserving existing behavior for other relationship types.
Example Usage
return MyModel::find(2)
->someRelationship()
->when(true, function($query) {
// $query is now BelongsToMany instance
return $query->wherePivotBetween('updated_at', ['2000-05-05', '2024-05-05']);
})
->get();
Marking as draft since tests are failing.
@Sajid-al-islam I was looking at your PR, the test fails because the withTrashed function in MorphTo thinks a query-builder for the model is passed, but in reality, the relation is passed. The argument in the callback ($query) (Eloquent/Relations/MorphTo.php:349) changes from "Illuminate\Database\Eloquent\Builder" to "Illuminate\Database\Eloquent\Relations\MorphTo", where the 'withTrashed' macro never exists.
I think this might be a way to proceed, but I think the macro-check needs to be done differently. The 'withoutTrashed' and 'onlyTrashed' in the same class use the same logic. Because this changes the real type of the argument in the callback from Eloquent\Builder to Eloquent\Relations\.. I think this must be treated with care and be seen as a breaking change.
@rikvdh thanks, I will look into it
Why don't you just add Conditionable to the base Relation class? Then it's consistent across relations and forwarding will work as normal so there's no concerns there
Also, in your example the variable name should be $relation as that's what's actually being passed in:
return MyModel::find(2)
->someRelationship()
- ->when(true, function($query) {
- // $query is now BelongsToMany instance
- return $query->wherePivotBetween('updated_at', ['2000-05-05', '2024-05-05']);
- })
+ ->when(true, function($relation) {
+ return $relation->wherePivotBetween('updated_at', ['2000-05-05', '2024-05-05']);
+ })
->get();
Hey there,
Feel free to submit a new PR with passing tests.