In this episode, we take a look at how to use API resources in Laravel to clean up the data we send from our backend to the frontend. Right now, we're sending way too much info—like user IDs and all the columns from our tables—which is not just messy but could potentially expose sensitive data. So, we need a better way to only include the data our frontend actually needs.
We'll walk through how to create a Laravel API resource for the Site
model. After generating a resource class, we go in and define exactly which fields to include (just the id
and domain
, for this example). This has the awesome effect of slimming down our API responses, making them safer and easier to work with.
We then update our controller to use the new resource, and on the frontend, we see that our data is now wrapped inside a data
property—useful for APIs but something to keep in mind when consuming this data in templates or components. We fix things up so our views work with the new structure, and confirm that only what we want (site ID and domain) is coming through.
The episode wraps up with a recommendation: do this for every model or response you send to the frontend. That way, you'll always have tidy, secure, and efficient data moving through your app!