In this episode, we dive deep into Laravel's handy tap()
function. If you haven’t used tap()
before, you'll see why it can be a really clever little tool to tidy up your code. We start with a simple example—updating a user record in a typical Laravel API controller. Normally, after calling $user->update()
, you might notice that it returns a Boolean (not the user instance), which isn't super convenient if you want to return the updated user. That's where tap()
comes in: it lets you perform an action on an object and still return that object, making your code much cleaner.
We then take a look at how tap()
works under the hood by peeking into Laravel's helpers. You'll see the function is beautifully simple, and you'll learn about both the callback style and the higher order proxy style for even more readable code.
After the basics, we go through a more complex example involving creating and associating addresses and countries for a user. This time, there's a focus on breaking your logic out into small, single-purpose methods, tying everything together with tap()
to keep the main controller methods concise and easy to follow. You'll see how helper methods, paired with tap()
, make your codebase more maintainable—especially as things get more complicated.
We also walk through updating an address, showing how these refactorings allow you to reuse methods cleanly, again leveraging tap()
for clarity. Along the way, you'll pick up practices for better code organization—even if it seems overkill at first. By the end of the video, you’ll have a handful of practical patterns for using tap()
, and you'll understand when using it is worthwhile (and when it might be a little much).
Overall, this episode gives you both a practical intro and a deeper dive into using tap()
to streamline your Laravel code, with clear examples you can use in your own projects.