0
votes

I'm stumped on what to do to fix this issue I'm having in laravel where the results of the models relationship returns empty/null relationship fields when I only want it to show "animals" with data when doing a GET call with a search string. For example in the response below in the "favorite_animals" field I only want the "animals" object with data to show in that array.

This is the endpoint localhost/api/v1/lists/2?search=honeybadger

    "name": "titleTwo",
        "description": "list two",
        "favorite_animals": [
            {
                "animals": null
            },
            {
                "animals": {
                    "id": 1,
                    "name": "HoneyBadger",
                    "description": "dgaf",
                    "created_at": "2021-07-30T22:49:36.000000Z",
                    "updated_at": "2021-07-30T22:49:36.000000Z"
                }
            },
            {
                "animals": null
            }
        ]

The following is the code block in the controller that queries the model data:

$list = UsersAnimalList::with(['favoriteAnimals.animals' => function($query) use($request){
$query->where('name', 'like', $request->input('search'));}])->get();

The following are the model relationships:

Model: UserAnimalList

public function favoriteAnimals(){
return $this->hasMany(UsersFavoriteAnimals::class, 'list_id', 'id');}

Model: UsersFavoriteAnimals

public function animals(){
return $this->hasOne(Animals::class, "id", "animals_id");}

Other Model but has no relationship method on them: Animals

I've tried using has() but that returned a empty response. I've tried changing the relationship from hasMany() to hasOne() it only changed from showing an empty array to a null;

I've also tried using the where() in an attempt to filter out the null generated relationship field "animals" but I get error saying the field doesn't exist.

2

2 Answers

0
votes

There are 2 things you can do:

  1. use the laravel build-in toArray() method to return the values inside an array, and up next use the php array_filter() function to remove the empty values

  2. You can create a collection and use the laravel build-in filter() function to remove the empty values from the data collection

0
votes

You can also possibly filter models based on relationship existence:

$list = UsersAnimalList::with(['favoriteAnimals.animals' => function($query) use($request) {
    $query->where('name', 'like', $request->input('search'));
}])->has('favoriteAnimals.animals')->get();

This is documented here