在 Laravel 中動態隱藏 API 字段的方法

我最近在 Laravel Brasil 社區看到一個問題,結果比看起來更有趣。想象一下你有一個 UsersResource 用下面的實現:
<?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 ]; } }
出于某種原因,您可能希望在另一個端點上重新使用該資源類,但隱藏email 字段。這篇文章就是告訴你如何實現這一點的。
如果你不知道 API Resources 是什么,請查看我之前關于這個的文章。
1- 初始化項目
有趣的東西從第3節開始.
composer create-project --prefer-dist laravel/laravel api-fields cd api-fields touch database/database.sqlite
編輯.env文件,刪除數據庫設置并使用 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- 路由
確保在 api.php 文件中創建一個路由。
Route::apiResource('/users', 'UsersController');
3- 控制器
控制器代表了期望的目標。在這個例子中,讓我們假設在用戶列表中,我們只想要所有用戶的名字,而在用戶顯示中,我們只想隱藏電子郵件地址。
<?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']); } }
為了達到這個目的,我們需要 UsersResourceCollection
和UsersResource
同時知道如何處理 hide 調用。
4- UsersResource 類
讓我們從 show 方法開始. UsersResource::make
將會返回 UsersResource
的對象. 因此,我們應該揭開 hide 的神秘面紗,它可以存儲我們期望從響應中移除的鍵.
<?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(); } }
大功告成! 現在我們可以訪問 http://api.dev/api/users/1 ,你會發現響應中已經沒有id 字段了。
{ "data": { "name": "Mr. Frederik Morar", "email": "[email protected]" } }
5- UsersResourceCollection 類
執行項目集合中的 index 方法, 我們需要作出如下修改:
(1) 確保 UsersResource::collection 返回 UsersResourceCollection 實例
(2) 在 UsersResourceCollection 上公開 hide 方法
(3) 將隱藏的字段傳遞給 UsersResource
關于 (1), 我們只需要重寫 UsersResource 中的 collection 方法
<?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(); } }
關于 (2) 和 (3) 我們需要修改 UsersResourceCollection 文件. 讓我們公開 hide 方法并使用隱藏字段處理集合。.
<?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(); } }
就是這么簡單! 現在我們訪問 http://api.dev/api/users 看到返回結果中沒有了 id 和 email 字段了如在 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- 總結
本文目標是讓Resource類通過隱藏一些在其他接口允許暴露的字段從而變得更加靈活。例如當我們請求/users接口時響應的數據是不包含avatar字段的,但是當請求/users/99時響應的數據里包含avatar字段。
我不推薦過度重復去請求API資源,因為它很可能會把簡單的事情變得更加復雜,所以說在請求的時候隱藏某些特定的字段是更簡單、更合理的解決方案。
以上所述是小編給大家介紹的在 Laravel 中動態隱藏 API 字段的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
您可能感興趣的文章:
相關文章
在thinkphp5.0路徑中實現去除index.php的方式
今天小編就為大家分享一篇在thinkphp5.0路徑中實現去除index.php的方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10PHP圖片等比縮放類SimpleImage使用方法和使用實例分享
這篇文章主要介紹了PHP圖片等比縮放類SimpleImage使用方法和使用實例分享,需要的朋友可以參考下2014-04-04
最新評論