05. Resolving the builder for later


Another example which kind of relates to what we looked at earlier is resolving the builder before we perform any logic on something under some sort of condition. Now we already saw earlier when we used the when method on eloquent that works really really nicely but sometimes your use case might change you might have some more complex logic that doesn't
fall under this so what you'd want to do in this case is use your post model initially without any kind of scoping at all and then I'm just going to comment this out then go ahead and perform some sort of if statement around here to continue to do this before you go ahead and grab back all of the results so it really depends but at least now you know you've got the option so you
can say post query because you don't have any need to scope this by the slug or anything like that first of all before you go ahead and perform some logic and then get this so this can be just sort of an initial return me the query builder so I can continue to do what I want with it without having to do this within an if statement which wouldn't make sense because you'd have to get the
query builder back before you start doing something just as an example of this and how this can clear things up depending if we bring back that include unpublished that we saw a little bit earlier if we were to now say post where published true or we can even reassign this it's really up to your style then if we come over and give this a refresh you can see that we we just die dump
on these posts let's change that we get one in here if we go ahead and say include unpublished true we get two the alternative to not using this would be to do something like this and then saying else post equals post get and then returning it like this and then moving the get to here so obviously what we just did by returning the builder first and then training
makes a lot more sense this will still work if we just set this to posts still works in exactly the same way but it's just a little bit messier so if we just revert this back to how we had it before resolving that builder first and then going ahead and starting to train things on tends to tidy things up a lot
7 episodes 23 mins


Ever used the Eloquent query() method in Laravel before? In this short course, we'll dive into what this method does, and demonstrate the ways it can be used.

Alex Garrett-Smith
Alex Garrett-Smith
Hey, I'm the founder of Codecourse!


No comments, yet. Be the first to leave a comment.