Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Add whenNested() or nested flag to when() for grouped conditions#58064

Unanswered
musiermoore asked this question inIdeas
Discussion options

AddwhenNested() ornested flag towhen() for grouped conditions

Closures passed intowhen() are currentlynot grouped automatically.
Because of this, mixedwhere /orWhere conditions are applied directly to the main query unless an extra nested closure is added.

Problem Example

->when($condition,fn ($q) =>$q->where('author_id',1)->orWhere('published',true));

This produces SQL like:

...AND author_id=1OR published= true

To ensure proper grouping today, you must write:

->when($condition,fn ($q) =>$q->where(fn ($q2) =>$q2->where('author_id',1)->orWhere('published',true)    ));

This becomes verbose and reduces readability.

Proposal

Introduce one of the following (or both, if desired):

1. New whenNested() method

->whenNested($condition,fn ($q) =>...)

This would automatically apply the callback inside a grouped where, so it would produce clean, grouped SQL:

...AND (author_id=1OR published= true)

2. Add a nested parameter to when()

->when($condition,fn ($q) =>..., nested:false)

nested defaults to false, preserving all existing behavior.

When set to true, the callback is executed inside a grouped where, and would also produce:

...AND (author_id=1OR published= true)

Summary

AddingwhenNested() or a nested parameter towhen() would simplify grouped conditional queries, prevent subtle logic errors, and improve readability while remaining fully backward compatible.

If this sounds useful, I’m happy to create a PR to implement it.

You must be logged in to vote

Replies: 1 comment 2 replies

Comment options

This becomes verbose and reduces readability.

Verbose is better than hidden under the carpet.

You must be logged in to vote
2 replies
@musiermoore
Comment options

@macropay-solutions using whenNested() makes it clear the closure will be grouped, so the behavior is explicit. Since it’s optional, it doesn’t affect existing code

@macropay-solutions
Comment options

You are right. The only downside to it is some overhead.

Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
Ideas
Labels
None yet
2 participants
@musiermoore@macropay-solutions

[8]ページ先頭

©2009-2025 Movatter.jp