Skip to content

[5.4] add tap to query builder#18284

Merged
taylorotwell merged 3 commits intolaravel:5.4from
BrandonShar:add-tap-to-query-builder
Mar 9, 2017
Merged

[5.4] add tap to query builder#18284
taylorotwell merged 3 commits intolaravel:5.4from
BrandonShar:add-tap-to-query-builder

Conversation

@BrandonShar
Copy link
Copy Markdown
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
Copy Markdown
Member

Interesting, what were you using this for?

@BrandonShar
Copy link
Copy Markdown
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
Copy Markdown
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
Copy Markdown
Member

Gotcha.

@JosephSilber
Copy link
Copy Markdown
Contributor

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

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

@BrandonShar
Copy link
Copy Markdown
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