In this episode, we're making a big improvement to how our Laravel app handles API responses. Right now, when someone logs in and we get user info from the backend, Laravel just spits out the whole user object as JSON. The problem with this is that it can expose way more data than we want—like every single field from the database. Not ideal!
So, we talk through how to use Laravel's API Resource classes to take control of what we're actually sending back. We first generate a UserResource and switch our route to use this resource for formatting the user data. By default, Laravel wraps the returned data in a data
property, which you can either adapt to on the frontend or, as shown here, disable entirely for a flatter response.
After we've set up the resource, we dive into customizing which fields are exposed. Instead of sending the full user object, we just pick out the id
, name
, and email
—nothing else. After making these changes, we check our API response again, and voilà! We’re returning just what we need, no sensitive or extra database fields getting leaked to the client. It's a much safer and cleaner approach for building your API.