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

[5.4] add tap to query builder #18284

Merged
merged 3 commits into from
Mar 9, 2017

Conversation

BrandonShar
Copy link
Contributor

I've run into a few situations lately (mainly parsing filters from query strings) where I ended up using when(1, $callback).

To make this a bit cleaner, I added a tap method to query builder to mimic the behavior found in collections.

@taylorotwell
Copy link
Member

Interesting, what were you using this for?

@BrandonShar
Copy link
Contributor Author

I've been parsing filters out of the query string on api endpoints. A simplified example of code looks like this:

return User::when(true, function ($query) use ($request) {  
    foreach ($request->except('sort', 'page') as $param => $value) { 
        $query->where($param, $value); 
    } 
})->get();

@BrandonShar
Copy link
Contributor Author

I'd love a cleaner way to filter by query params, but it would definitely require some discussion since the solution would likely be pretty opinionated.

@taylorotwell taylorotwell merged commit a4fe12a into laravel:5.4 Mar 9, 2017
@taylorotwell
Copy link
Member

Gotcha.

@JosephSilber
Copy link
Member

@BrandonShar BTW, you can pass an array directly to where:

return User::where($request->except('sort', 'page'))->get();

@BrandonShar
Copy link
Contributor Author

@JosephSilber thanks for the advice, I'll keep that in mind. In this case though, I simplified my example a good bit. In my real use case, I check for things like * to indicate wild card and whether scopes exist for certain filters.

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