I recently saw a question in the Laravel Brasil community, and the result was It looks more interesting. Imagine you have a UsersResource
implemented with the following:
<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\Resource; class UsersResource extends Resource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'name' => $this->name, 'email' => $this->email ]; } }
For some reason, you might want to reuse that resource class on another endpoint, but hide email
Field. This article tells you how to achieve this.
If you don’t know what API Resources
are, please check out my previous article about this.
- First Impression on API Resources
- API Resources with Nested Relationship
1- Initialization project
Interesting stuff Start with Section 3.
composer create-project --prefer-dist laravel/laravel api-fields cd api-fields touch database/database.sqlite
Edit the .env
file, remove the database settings and continue setting up the project using SQLite
DB_CONNECTION=sqlite
php artisan migrate php artisan make:resource UsersResource php artisan make:resource --collection UsersResourceCollection php artisan make:controller UsersController php artisan tinker factory(App\User::class)->times(20)->create(); quit
2- Routing
Make sure to create a route in the api.php
file.
Route::apiResource('/users', 'UsersController');
3- Controller
The controller represents the desired goal. In this example, let's assume that in the users list we only want the names of all users, and in the users display we only want to hide the email addresses.
<?php namespace App\Http\Controllers; use App\Http\Resources\UsersResource; use App\User; class UsersController extends Controller { /** * Display a listing of the resource. * * @param User $user * @return \Illuminate\Http\Response */ public function index(User $user) { return UsersResource::collection($user->paginate())->hide(['id', 'email']); } /** * Display a user. * * @param User $user * @return \Illuminate\Http\Response */ public function show(User $user) { return UsersResource::make($user)->hide(['id']); } }
To achieve this, we need UsersResourceCollection
and UsersResource
to both know how to handle hide
calls.
4- UsersResource class
Let’s start with the show
method. UsersResource::make
will return UsersResource
Object. Therefore, we should demystify hide
which stores the keys we wish to remove from the response.
<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\Resource; class UsersResource extends Resource { /** * @var array */ protected $withoutFields = []; /** * Transform the resource into an array. * * @param \Illuminate\Http\Request * @return array */ public function toArray($request) { return $this->filterFields([ 'id' => $this->id, 'name' => $this->name, 'email' => $this->email ]); } /** * Set the keys that are supposed to be filtered out. * * @param array $fields * @return $this */ public function hide(array $fields) { $this->withoutFields = $fields; return $this; } /** * Remove the filtered keys. * * @param $array * @return array */ protected function filterFields($array) { return collect($array)->forget($this->withoutFields)->toArray(); } }
Done! Now we can access http: //api.dev/api/users/1
, you will find that there is no id
field in the response.
{ "data": { "name": "Mr. Frederik Morar", "email": "darryl.wilkinson@example.org" } }
5- UsersResourceCollection class
Execute the index
method in the project collection, we need to make the following modifications:
- (1) Ensure
UsersResource::collection
ReturnsUsersResourceCollection
instance - (2) Public
hide
method# on
UsersResourceCollection ##(3) Pass the hidden fields to - UsersResource
collection in UsersResource
Methods
<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\Resource; class UsersResource extends Resource { public static function collection($resource) { return tap(new UsersResourceCollection($resource), function ($collection) { $collection->collects = __CLASS__; }); } /** * @var array */ protected $withoutFields = []; /** * Transform the resource into an array. * 将资源转换为一个数组 * * @param \Illuminate\Http\Request * @return array */ public function toArray($request) { return $this->filterFields([ 'id' => $this->id, 'name' => $this->name, 'email' => $this->email ]); } /** * Set the keys that are supposed to be filtered out. * 设置需要隐藏过滤掉的键 * * @param array $fields * @return $this */ public function hide(array $fields) { $this->withoutFields = $fields; return $this; } /** * Remove the filtered keys. * 删除隐藏的键 * * @param $array * @return array */ protected function filterFields($array) { return collect($array)->forget($this->withoutFields)->toArray(); } }Regarding (2) and (3) we need to modify the
UsersResourceCollection file. Let’s expose the
hide method and use hidden fields to handle the collection. .
<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\ResourceCollection; class UsersResourceCollection extends ResourceCollection { /** * @var array */ protected $withoutFields = []; /** * Transform the resource collection into an array. * * @param \Illuminate\Http\Request * @return array */ public function toArray($request) { return $this->processCollection($request); } public function hide(array $fields) { $this->withoutFields = $fields; return $this; } /** * Send fields to hide to UsersResource while processing the collection. * 将隐藏字段通过 UsersResource 处理集合 * * @param $request * @return array */ protected function processCollection($request) { return $this->collection->map(function (UsersResource $resource) use ($request) { return $resource->hide($this->withoutFields)->toArray($request); })->all(); } }It’s that simple! Now we visit
http://api.dev/api/users and see that
id and
are not included in the returned results. The email field is as specified in the method in
UsersController.
{ "data": [{ "name": "Mr. Frederik Morar" }, { "name": "Angel Daniel" }, { "name": "Brianne Mueller" }], "links": { "first": "http://lab.php71/api-fields-2/public/api/users?page=1", "last": "http://lab.php71/api-fields-2/public/api/users?page=7", "prev": null, "next": "http://lab.php71/api-fields-2/public/api/users?page=2" }, "meta": { "current_page": 1, "from": 1, "last_page": 7, "path": "http://api-fields.lab.php71/api/users", "per_page": 3, "to": 3, "total": 20 } }6- SummaryThe goal of this article is to let the
Resource class pass the hidden Some fields are allowed to be exposed in other interfaces to make them more flexible. For example, when we request the
/users interface, the response data does not contain the
avatar field, but when we request
/users/99, the response data contains
avatarField.