Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Relationships values should always be an array #524

Closed
mwalid-trackbar opened this issue Dec 20, 2022 · 2 comments
Closed

Relationships values should always be an array #524

mwalid-trackbar opened this issue Dec 20, 2022 · 2 comments

Comments

@mwalid-trackbar
Copy link

mwalid-trackbar commented Dec 20, 2022

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();
@binaryk
Copy link
Collaborator

binaryk commented Dec 20, 2022

Thanks @mwalid-trackbar for diving into this.

@binaryk
Copy link
Collaborator

binaryk commented Feb 5, 2023

Solved! Thank you!

@binaryk binaryk closed this as completed Feb 5, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants