Skip to content

Conversation

@gdebrauwer
Copy link
Contributor

@gdebrauwer gdebrauwer commented Jan 6, 2026

This PR adds the ability to add "where subquery between values" clauses to the query builder.

It is already possible to add a "where subquery value" clause to a query builder, so I assumed this also worked on 'where between' clauses but that is not the case.

$query->whereBetween($subquery, [$minValue, $maxValue])

Why would this be needed? Well, let's say you have users and users have posts. Let's say you need to query users whose latest post was created between one and two months ago. Eloquent currently does not provide a way to write that query without having to resort to the "whereRaw" method, but this PR fixes that so you can write the following query:

$users = User::query()
	->whereBetween(
		Post::query()
			->select('created_at')
			->whereColumn('posts.user_id', 'users.id')
			->latest()
			->limit(1),
		[now()->subMonths(2), now()->subMonth()],
	)
	->get();

@gdebrauwer gdebrauwer changed the title [12.x] Support whereBetween with subquery [12.x] Support "where subquery between values" Jan 6, 2026
@shaedrich
Copy link
Contributor

shaedrich commented Jan 6, 2026

Have you also considered this case?

$users = User::query()
	->whereBetween(
		Post::query()
			->select('created_at')
			->whereColumn('posts.user_id', 'users.id')
			->latest()
			->limit(2), // <!-- select both min and max
	)
	->get();

@gdebrauwer
Copy link
Contributor Author

gdebrauwer commented Jan 6, 2026

@shaedrich I'm not sure what you mean? 🤔 Could you elaborate?

@shaedrich
Copy link
Contributor

shaedrich commented Jan 6, 2026

@gdebrauwer Sure: You implemented an option to pass a sub query builder instance for either the min or the max value or both. However, these are passed as separate arguments. Some people might want to select both the min and the max value within the same sub query and pass the builder instance as a single, combined argument to whereBetween(), wherein the two values are extracted from the query and assigned to $min and $max respectively.

Hope, that makes it a little more comprehensible.

Edit: After reading your diff again, I realised, you implemented this for column, not for $values. Nevermind.

@taylorotwell taylorotwell merged commit 79d902f into laravel:12.x Jan 6, 2026
71 checks passed
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