laravel / laravel/framework

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

Open
#53,292 12 comments 0 reactions 0 assignees View on GitHub
help wanted
Dominant language
PHP
Stars
34.9k
Forks
12k
Avg merge
17h 57m
Merged PRs (30d)
182

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.

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the relationship query shown in the issue, focusing on the when helper and the BelongsToMany relationship. Trace which object is passed into the closure and add a regression test covering wherePivotBetween; done means the closure receives the relationship instance and its relationship-specific methods work.

Written by the indexing model from the issue text.

Assessment

Tech stack
laravel, php
Domain
backend, databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.