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

Add whenGrouped to query builders. #54312

Closed
wants to merge 2 commits into from
Closed

Conversation

hailwood
Copy link
Contributor

Purpose of this PR

The Laravel query builder supports both the helpful when method for conditionally modifying the query, and also nested where calls for grouping conditions.

However, if you want to combine these two method you end up with a difficult to read boilerplate chain of fn(Builder $query) => $query->where(fn(Builder $query) => $query->...) E.g.

$query
  ->where('column_a', 'value_a')
  ->when($condition, fn(Builder $query) => $query->where(fn(Builder $query) => $query
    ->where('column_b', 'value_b')
    ->orWhere('column_c', 'value_c')
  ));

This PR adds a new whenGrouped method to allow the above to become

$query
  ->where('column_a', 'value_a')
  ->whenGrouped($condition, fn(Builder $query) => $query
    ->where('column_b', 'value_b')
    ->orWhere('column_c', 'value_c')
  );

We could change the name of this method, e.g. maybe whenWhere might be better?

Tests?

I investigated adding tests for this, but concluded that there's really nothing to test here as we're just adding some syntactic sugar.

@shaedrich
Copy link
Contributor

shaedrich commented Jan 23, 2025

We could change the name of this method, e.g. maybe whenWhere might be better?

Yeah, that sounds more intuitive. Especially with already that many where methods, this should clearly communicate what it does 👍🏻

Is it intentional that, in your example, you first call when then where, but in your implementation, you do it the other way round?

Will this only support a callback or all possible values for both where (e.g. array) and when (e.g. bool)?

@taylorotwell
Copy link
Member

The naming makes me think of groupBy.

@hailwood
Copy link
Contributor Author

Hey @taylorotwell,

Would you be interested in this PR with a different name, or something you're not interested in at all?

(NBD either way, it's easy to add as a macro anyway).

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