How to filter laravel model relationships where if the relationship is empty/null it should not show the object

  eloquent, laravel, model

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.

Source: Laravel

Leave a Reply