laravel / framework

The Laravel Framework.
https://laravel.com
MIT License
32.64k stars 11.04k forks source link

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

Open Sajid-al-islam opened 4 days ago

Sajid-al-islam commented 4 days ago

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();
crynobone commented 3 days ago

Marking as draft since tests are failing.

rikvdh commented 2 days ago

@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.

Sajid-al-islam commented 2 days ago

@rikvdh thanks, I will look into it