In this episode, we focus on all the different ways you can access request data in Laravel, especially now that there's a new fluent
method you might not have seen before. We start by covering the basics, like grabbing a value from the request directly or using request()->all()
to get everything as an array. Then, we compare that to using collections, which can be handy, but collections aren't always the best fit when you just need to pass basic data around.
The main event is introducing the fluent
object. We show how Laravel's Fluent object lets you work with request data in a more object-like and convenient way. It's super easy to access properties ($data->name
), it's null-safe (so you won't run into those annoying undefined index errors with missing data), and it can even be mutated or converted to JSON with ease.
We walk through setting up some example data, converting it to a fluent object, and show how it's easier to use than arrays or collections in many situations. As a practical example, we show how you might pass a Fluent object to an action class, making the code cleaner and safer, since you don't need to constantly check for values or worry about missing keys.
To wrap up, we chat about when to use Fluent objects versus custom data objects, but conclude that for many use-cases, especially when you're just moving request data around your app, going fluent makes your code much nicer to work with. So, next time you're handling request data, give the request()->fluent()
method a shot!