Skip to main content

Optimize Search JSON with API Resources

Premium
17 min read

We ended up the previous lesson by returning a huge JSON from the property search results. Let's spend this lesson optimizing it and showing only the data that we really need to return.


Goals of This Lesson

  • Transform the returned data using Eloquent API Resources
  • Create Accessors to show Addresses and Beds list in a human-friendly way
  • Fix search results order/limit: showing only ONE apartment per property

By the end of this lesson, we will have this nice JSON structure in search results:

Property search beds


Shorter JSON: Eloquent API Resources

A quick reminder of how it looks now.

Endpoint: /api/search?city_id=1&adults=2&children=1

Result JSON:...

The Full Lesson is Only for Premium Members

Want to access all of our courses? (30 h 33 min)

You also get:

55 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

AV
Andrea Verrecchia ✓ Link copied!

Does it make sense to check with middleware the actual presence of at least one apartment per property and add a method such as testPropertyHasAtLeastOneApartment? Then check that if a property has no associated apartments, return a status check of, for example, 422.

PK
Povilas Korop ✓ Link copied!

I don't think this is a very realistic scenario, because withWhereHas() ensures that those properties would be filered out, as I understand. But if you want a separate check, you may add it, I guess.

N
nazzalra ✓ Link copied!

on the Feature Test for Bed String part from the Fifth step, when create a Bed, the room_id value should be $secondRoom->id not $room->id right?

PK
Povilas Korop ✓ Link copied!

Yes, of course! Well spotted, fixed in the tutorial text, thanks!

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.