Home > OS >  Laravel 7 API Resource showing only data that contains relationship
Laravel 7 API Resource showing only data that contains relationship

Time:02-19

This my code stored in my API Controller:

return ApartmentResource::collection(Apartment::with(['sponsors'])->paginate(5));

It shows all Apartments, someone have the sponsor array empty, someone not.

How i can show only the Apartments that actually have sponsors?

CodePudding user response:

You can use the has() method

https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence

return ApartmentResource::collection(Apartment::has('sponsors')->with(['sponsors'])->paginate(5));

with() simply eager loads the sponsors: https://laravel.com/docs/9.x/eloquent-relationships#eager-loading

CodePudding user response:

use array_filter()

example:

$result = array_filter($array);

array_filter() remove empty array elements from array.

  • Related