Skip to content

Relationships values should always be an array #524

Closed
@mwalid-trackbar

Description

@mwalid-trackbar

Schema

User has many Post
Post has many Note
Note belong to User

Policy

Allow show for note when the note belongs to user.

class NotePolicy
{
    public function show(User $user, Note $note)
    {
       return $note->user_id == $user->id;
    }
}

Database

Post

id
1

User

id
1
2

Note

id user_id
1 2
2 1

Request

GET /posts?related=note
Whenever a user fetches a post it would load the notes but only the ones belonging to the user because of the NotePolicy.

Response

Actual

{
   .....
   "relationships":{
      "notes":{
         "1":{
            "id":"2",
            "type":"notes"
         }
      }
   }
   .....
}

Expected

{
   .....
   "relationships":{
      "notes":[
         {
            "id":"2",
            "type":"notes"
         }
      ]
   }
   .....
}

Root cause

  1. Resolve eager field uses allowToShow to nullify notes where the user is not allowed to access https://github.com/BinarCode/laravel-restify/blob/7.x/src/Fields/EagerField.php#L69
  2. Resolve relationship uses filter on the collection to remove nulls https://github.com/BinarCode/laravel-restify/blob/7.x/src/Repositories/Repository.php#L530

Post loaded from db

{
   "id":1,
   "notes":[
      {
         "id":"1",
         "type":"notes"
      },
      {
         "id":"2",
         "type":"notes"
      }
   ]
}

Post notes are filtered via allowToShow (step 1)

{
   "id":1,
   "notes":[
     null,
      {
         "id":"2",
         "type":"notes"
      }
   ]
}

Post notes after removing nulls via filter (step 2)

{
   "id":1,
   "notes":{
      1 => {
         "id":"2",
         "type":"notes"
      }
   }
}

Suggested fix

Replace

return $items->filter();

with

return $items->filter()->values();

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions