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

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

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

Sajid-al-islam
Copy link

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 Sajid-al-islam changed the title [Master] Fixing when helper issue in relation instance [Master] Fixing Eloquent Builder instance in relation class inside closure Nov 18, 2024
@crynobone
Copy link
Member

Marking as draft since tests are failing.

@crynobone crynobone marked this pull request as draft November 19, 2024 13:26
@crynobone crynobone changed the title [Master] Fixing Eloquent Builder instance in relation class inside closure [12.x] Fix Eloquent Builder instance in relation class inside closure Nov 19, 2024
@rikvdh
Copy link
Contributor

rikvdh commented Nov 19, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants