'Laravel 7 API Resource showing only data that contains relationship

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?



Solution 1:[1]

use array_filter()

example:

$result = array_filter($array);

array_filter() remove empty array elements from array.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1