Fetching questions under poll in restful api ( nested data )

Step 01: In PollController changing setup like below from previous setup

public function show($id) {
	$poll = Poll::find($id);
	if(is_null($poll)){
		return response()->json(null,404);
	}
	$poll = Poll::with( [ 'questions'=>function($query){
				$query->select(['title', 'poll_id']);
			}] )->findOrFail($id);
	$response = new PollResource($poll);
	return response()->json($response,200);
}

Please note from above, in controller we have added eager loading with() method to fetch associated question data for a poll. Morever, we also restricted number of rows from question data to only title and poll_id.   

Step 02: In PollResource.php changing setup like below
namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class PollResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
     */
    public function toArray($request)
    {
        return [
            'title' => $this->title,
            'created_at' => $this->created_at->toDateString(),
            'questions' => $this->questions
        ];
    }
}

Here, in PollResource.php we have added the Poll model association so that question data for a poll gets returend as JSON format. Otherwise despite of association setup in PollController this associated data will not be loaded.


To check it endpoint url will be like below for browsing all poll records with associated question records which will be nested under Poll JSON array

http://localhost:8000/api/polls/3
HTTP Verb: GET

Related Posts


Building RESTful APIs in Laravel

Seeding Poll data

Seeding Question data for a poll

Pagination for poll in restful api

Uploading image in restful api