Using transformers to transform api response data

Sometimes our api response data need to be transferred in certain way to achive our desired need. For example, formatting date field in certain way or restricting number of fields from showing actual fields or shortening title of a post and so on. In laravel we can achieve that using Resources.

In this post we will be creating PollResource to restrict number of fields and also to format date fields. The desired snippet is given below.

Step 01: Creating PollResource with artisan command
php artisan make:resource PollResource

Step 02: Adding necessary changes in toArray() method in PollResource

public function toArray($request)
{
	return [
		'title' => $this->title,
		'created_at' => $this->created_at->toDateString()
	];
}

Step 03: Changing show() method of PollController like below for a resource

public function show($id) {
	$poll = Poll::find($id);
	if(is_null($poll)){
		return response()->json(null,404);
	}
	$response = new PollResource($poll);
	return response()->json($response,200);
}

Step 04: Changing index() method of PollController to transform collection of data

public function index() { //dd(request('search_title'));
	$polls = Poll::when( request('search_title'), function ($query) {
				$query->where('title', 'like', '%'.request('search_title').'%' );
			})->get();
	$polls = PollResource::collection($polls);
	return response()->json($polls,200);
}  


In all the cases above, only title and formatted date will be shown as api response both for a resource or collection of data. This is how transformer is used in laravel to transform actual data to desired one.

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