Tuesday, March 7, 2017

Serialize: Entity/Array of entites as JSON HTTP response

I have problem with sending entities as json response. I'm using Lumen 5.4 and Doctrine2.

I have an User Entity and User Repository. Request hits controller and I have two API routes: /api/users/{userID} and /api/users.

In first case I want to return single User Entity as JSON, i.e:

{
    "id": 1,
    "username": "user1"
}

I realized that by implementing \Illuminate\Contracts\Support\Jsonable in User Entity and implementing custom toJson() method. Now in controller I can just:

public function getOne($userID){
    return $this->repository->findByID($userID);
}

And when I hit /api/users/1 result is as requested.

But when I query for many users and getting array of entities my result is:

[
    {},
    {},
    {}
]

The route handler is:

public function getMany(){
    return $this->repository->find(); // returns array of entities
}

How to get array of entities serialized properly?



via rgwsk65

Advertisement