Skip to content

#3 Build Your Api Resource

php anonymous edited this page Aug 17, 2022 · 1 revision

It is common knowledge in the Laravel framework that you can control everything large and small, even in the fields and columns in the table and here in the API

namespace Modules\Test\Transformers;

use Illuminate\Http\Resources\Json\JsonResource;

class TestResources extends JsonResource {
	/**
	 * Transform the resource collection into an array.
	 *
	 * @param  \Illuminate\Http\Request
	 * @return array
	 */
	public function toArray($request) {
		return [
			'id'         => $this->id,
			'title'      => $this->title,
			'desc'       => $this->desc,
			'status'     => $this->status,
			'file'       => $this->file,
			'created_at' => $this->created_at,
			'updated_at' => $this->updated_at,
		];
	}
}

See this example. You can tell the lynx the fields that you want to display or hide, and from here you can change the shape of the fields in a way that makes you comfortable This example of the package nwidart/laravel-modules

The same step can be done with the general Laravel framework

namespace App\Http\Resource;

use Illuminate\Http\Resources\Json\JsonResource;

class TestResources extends JsonResource {
	/**
	 * Transform the resource collection into an array.
	 *
	 * @param  \Illuminate\Http\Request
	 * @return array
	 */
	public function toArray($request) {
		return [
			'id'         => $this->id,
			'title'      => $this->title,
			'desc'       => $this->desc,
			'status'     => $this->status,
			'file'       => $this->file,
			'created_at' => $this->created_at,
			'updated_at' => $this->updated_at,
		];
	}
}
Clone this wiki locally