[6.x] Allow callback scopes on Query Builder#30299
Closed
deleugpn wants to merge 2 commits intolaravel:6.xfrom
Closed
[6.x] Allow callback scopes on Query Builder#30299deleugpn wants to merge 2 commits intolaravel:6.xfrom
deleugpn wants to merge 2 commits intolaravel:6.xfrom
Conversation
oliverquynh
reviewed
Oct 16, 2019
|
|
||
| public function testApplyInvokableScope() | ||
| { | ||
| $result = DB::table('posts')->apply(new PostFrom2017Scope)->get(); |
Contributor
There was a problem hiding this comment.
I think CreatedIn2017Scope is more suitable? or What about this?
$result = DB::table('posts')->apply((new CreatedInYearScope(2017)))->get();
Contributor
Author
There was a problem hiding this comment.
I don't think that test class is relevant
Contributor
Author
|
I just learned about |
Member
|
OK, can you PR a documentation update for |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Laravel Query Builder allow for some pretty dynamic code execution. We can pass a
callbacktoselect,addSelect,where,joinand so on. However, we cannot pass a callback/closure togroupBy.It's been a while since I've wanted to apply any dynamic scope to Query Builder and this time, instead of contributing just to
groupByI thought I'd give it a shot.How it works
This will send the Query Builder to the callable method (if
MyDesiredScopeis callable) and let it mutate the Query Builder. I've been doing a lot of this withwherealready and it works great:I just had the need to do that at the
groupByclause instead and noticed I couldn't, hence the contribution to a broader audience.Signature
applywill accept a singleScope, multiple arguments of scope or an array of Scopes. all cases are covered by tests.Docs: laravel/docs#5533