Search code examples
phplaravelapiforeign-keys

laravel 8 API displaying title or name of a foreign key


I have an API with different parts that contains many foreign keys, like category_id for posts and categories , user_id for users and posts , parent_id for categories and subcategories and ...

so for example , i have a post details json response :

 "post": {
        "id": 1,
        "category_id": 2,
        "user_id": 1,
        "title": "Is there a vaccine for COVID-19?",
        "body": "Yes there are now several vaccines that are in use. The first mass vaccination programme started in early December 2020 and the number of vaccination doses administered is updated on a daily basis here. At least 13 different vaccines (across 4 platforms) have been administered.\r\n\r\nThe Pfizer/BioNtech Comirnaty vaccine was listed for WHO Emergency Use Listing (EUL) on 31 December 2020. The SII/Covishield and AstraZeneca/AZD1222 vaccines (developed by AstraZeneca/Oxford and manufactured by the State Institute of India and SK Bio respectively) were given EUL on 16 February. The Janssen/Ad26.COV 2.S developed by Johnson & Johnson, was listed for EUL on 12 March 2021. The Moderna COVID-19 vaccine (mRNA 1273) was listed for EUL on 30 April 2021 and the Sinopharm COVID-19 vaccine was listed for EUL on 7 May 2021. The Sinopharm vaccine is produced by Beijing Bio-Institute of Biological Products Co Ltd, subsidiary of China National Biotec Group (CNBG). The Sinovac-CoronaVac was listed for EUL on 1 June 2021.",
        "study_time": "2",
        "likes": 5,
        "dislikes": 1,
        "created_at": "2021-06-26T16:40:59.000000Z",
    },
    "comments": [
        {
            "id": 1,
            "parent_id": null,
            "name": "person1",
            "email": "[email protected]",
            "comment": "not good",
            "likes": 0,
            "dislikes": 2,
            "replies": [
                {
                    "id": 2,
                    "parent_id": 1,
                    "name": "person2",
                    "email": "[email protected]",
                    "comment": "ok",
                    "likes": 1,
                    "dislikes": 0,
                    "replies": [
                        {
                            "id": 3,
                            "parent_id": 2,
                            "name": "person3",
                            "email": "[email protected]",
                            "comment": "good",
                            "likes": 0,
                            "dislikes": 0
                        }
                    ]
                }
            ]
        }
    ],
    "post_views": 10
}

as you can see in this post i have category_id and user_id and parent_id for comments

how can i display title of category or name of user instead of their ID in json response?


Solution

  • If you want to customise how an Eloquent model is serialized, you can do so using Eloquent resources.

    You could create a PostResource which defines how you want to serialize your Post model. As an example:

    class PostResource extends JsonResource
    {
        /**
         * Transform the resource into an array.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return array
         */
        public function toArray($request)
        {
            return [
                'id' => $this->id,
                'category' => $this->category->name,
                'user' => $this->author->name,
                'comments' => CommentResource::collection($this->comments),
            ];
        }
    }
    

    Notice that you can call other Resource classes to perform customisation of nested relationships.

    You might also create a CommentResource and RepliesResource to do mappings for those too.

    Then you would return your PostResource, for example:

    return new PostResource(Resource::first());