laravel/framework

Conditional (when helper) gives back Eloquent Builder instance inside the closure instead of the relationship instance

Ouverte

#53 292 ouverte le 24 oct. 2024

 (12 commentaires) (0 réaction) (0 personne assignée)PHP (11 951 forks)batch import
help wanted

Métriques du dépôt

Stars
 (34 869 étoiles)
Métriques de merge PR
 (Merge moyen 1j 22h) (129 PRs mergées en 30 j)

Description

Laravel Version

11.28.1

PHP Version

8.3

Database Driver & Version

No response

Description

Inside the when closure you will not get a relationship instance, so any specific relationship function will not be available.

Expected: $query to be BelongsToMany instance

Actual: $query is a Illuminate\Database\Eloquent\Builder instance

Ex. BelongsToMany relationships, here you will not be able to call the wherePivot*-methods.

return MyModel::find(2)
->someRelationship()
->when(true, function($query) {
        logger($query::class); // Illuminate\Database\Eloquent\Builder

        $query->wherePivotBetween('updated_at', ['2000-05-05', '2024-05-05']); 
    return $query;
})->get();

Steps To Reproduce

Create a model any kind of relationship and and fire a query that uses the relationship. Like in the example above.

Guide contributeur