In this episode, we dive into the optional()
helper in Laravel and its super useful callback feature. If you haven't used optional()
before, don't worry—we start from the basics, experimenting with null values and showing how it makes working with potentially null relationships (like a user's address) a lot simpler compared to ternary checks or if statements.
After covering the basics, we explore the recent update that lets you pass a callback to optional()
. It's pretty slick: instead of just calling a method on something that might be null, you can now run a whole block of logic safely, but only if the value actually exists! We take a look at the source code to see how it works under the hood.
Next, we walk through a practical example using a user and their address. You’ll see how you might update an address if it exists, and how much tidier this gets when you use the callback. This comes in handy when you want to do more complex operations than just a single method call.
We wrap up by contrasting this approach with the old way of using if statements, demonstrating how the callback keeps your code cleaner and more readable. If you're ready to make your code a bit more elegant when dealing with nullable relationships or values, this episode will show you exactly how to do that!