In this episode, we look at a common scenario when working with query builders in Laravel: whether to resolve (grab) the builder before or after applying various pieces of logic—especially when those decisions depend on certain conditions.
We kick off by revisiting how the when
method can help keep queries tidy, but then shift to cases where your conditional logic is more complex and just doesn’t fit neatly into a when
statement. Here, we see why it’s often handy to grab the query builder up-front with no initial scoping. This way, you can set up your if
statements and any logic you need, then apply filters or transformations as required, before finally getting your results.
Through the example with the include unpublished
flag, we see both the clean and the (much messier) alternative approach that ends up with lots of repeated code or awkward branching. Ultimately, we show that resolving the builder first usually leads to cleaner, easier-to-follow code. You'll come away understanding when it makes sense to stick with the builder, and how that choice can tidy up your queries.