framework icon indicating copy to clipboard operation
framework copied to clipboard

[12.x] Fix Eloquent Builder instance in relation class inside closure

Open Sajid-al-islam opened this issue 1 year ago • 3 comments

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();

Sajid-al-islam avatar Nov 18 '24 07:11 Sajid-al-islam

Marking as draft since tests are failing.

crynobone avatar Nov 19 '24 13:11 crynobone

@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 avatar Nov 19 '24 18:11 rikvdh

@rikvdh thanks, I will look into it

Sajid-al-islam avatar Nov 20 '24 05:11 Sajid-al-islam

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();

calebdw avatar Apr 12 '25 04:04 calebdw

Hey there,

Feel free to submit a new PR with passing tests.

crynobone avatar Apr 14 '25 03:04 crynobone