校园春色亚洲色图_亚洲视频分类_中文字幕精品一区二区精品_麻豆一区区三区四区产品精品蜜桃

主頁(yè) > 知識(shí)庫(kù) > 在 Laravel 中動(dòng)態(tài)隱藏 API 字段的方法

在 Laravel 中動(dòng)態(tài)隱藏 API 字段的方法

熱門標(biāo)簽:杭州語(yǔ)音電銷機(jī)器人 泊頭在哪里辦理400電話 欣思維地圖標(biāo)注 江西電銷機(jī)器人收費(fèi) 天潤(rùn)融通外呼系統(tǒng)好嗎 江門回?fù)芡夂粝到y(tǒng) 高德地圖標(biāo)注位置怎么標(biāo)注 電銷機(jī)器人沒(méi)有效果怎么樣 高德地圖標(biāo)注店鋪收費(fèi)嗎

我最近在 Laravel Brasil 社區(qū)看到一個(gè)問(wèn)題,結(jié)果比看起來(lái)更有趣。想象一下你有一個(gè) UsersResource 用下面的實(shí)現(xiàn):

?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
  ];
 }
}

出于某種原因,您可能希望在另一個(gè)端點(diǎn)上重新使用該資源類,但隱藏email 字段。這篇文章就是告訴你如何實(shí)現(xiàn)這一點(diǎn)的。

如果你不知道 API Resources 是什么,請(qǐng)查看我之前關(guān)于這個(gè)的文章。

  • First Impression on API Resources
  • API Resources with Nested Relationship

1- 初始化項(xiàng)目

有趣的東西從第3節(jié)開(kāi)始.

composer create-project --prefer-dist laravel/laravel api-fields
cd api-fields
touch database/database.sqlite

編輯.env文件,刪除數(shù)據(jù)庫(kù)設(shè)置并使用 SQLite

DB_CONNECTION=sqlite

繼續(xù)設(shè)置項(xiàng)目

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 文件中創(chuàng)建一個(gè)路由。

Route::apiResource('/users', 'UsersController');

3- 控制器

控制器代表了期望的目標(biāo)。在這個(gè)例子中,讓我們假設(shè)在用戶列表中,我們只想要所有用戶的名字,而在用戶顯示中,我們只想隱藏電子郵件地址。

?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']);
 }
}

為了達(dá)到這個(gè)目的,我們需要 UsersResourceCollection UsersResource 同時(shí)知道如何處理 hide 調(diào)用。

4- UsersResource 類

讓我們從  show 方法開(kāi)始.  UsersResource::make 將會(huì)返回  UsersResource 的對(duì)象. 因此,我們應(yīng)該揭開(kāi)  hide 的神秘面紗,它可以存儲(chǔ)我們期望從響應(yīng)中移除的鍵.

?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();
 }
}

大功告成! 現(xiàn)在我們可以訪問(wèn) http://api.dev/api/users/1 ,你會(huì)發(fā)現(xiàn)響應(yīng)中已經(jīng)沒(méi)有id 字段了。

{
 "data": {
 "name": "Mr. Frederik Morar",
 "email": "darryl.wilkinson@example.org"
 }
}

5- UsersResourceCollection 類

執(zhí)行項(xiàng)目集合中的 index 方法, 我們需要作出如下修改:

(1) 確保  UsersResource::collection 返回 UsersResourceCollection 實(shí)例

(2) 在  UsersResourceCollection 上公開(kāi) hide 方法

(3) 將隱藏的字段傳遞給  UsersResource

關(guān)于 (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.
  * 將資源轉(zhuǎn)換為一個(gè)數(shù)組
  * 
  * @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.
  * 設(shè)置需要隱藏過(guò)濾掉的鍵
  * 
  * @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();
 }
}

關(guān)于 (2) 和 (3) 我們需要修改 UsersResourceCollection 文件. 讓我們公開(kāi) 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.
  * 將隱藏字段通過(guò) 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();
 }
}

就是這么簡(jiǎn)單! 現(xiàn)在我們?cè)L問(wèn) http://api.dev/api/users  看到返回結(jié)果中沒(méi)有了 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- 總結(jié)

本文目標(biāo)是讓Resource類通過(guò)隱藏一些在其他接口允許暴露的字段從而變得更加靈活。例如當(dāng)我們請(qǐng)求/users接口時(shí)響應(yīng)的數(shù)據(jù)是不包含avatar字段的,但是當(dāng)請(qǐng)求/users/99時(shí)響應(yīng)的數(shù)據(jù)里包含avatar字段。

我不推薦過(guò)度重復(fù)去請(qǐng)求API資源,因?yàn)樗芸赡軙?huì)把簡(jiǎn)單的事情變得更加復(fù)雜,所以說(shuō)在請(qǐng)求的時(shí)候隱藏某些特定的字段是更簡(jiǎn)單、更合理的解決方案。

以上所述是小編給大家介紹的在 Laravel 中動(dòng)態(tài)隱藏 API 字段的方法,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!

您可能感興趣的文章:
  • laravel框架 api自定義全局異常處理方法
  • 基于laravel制作APP接口(API)
  • 詳解Laravel5.6 Passport實(shí)現(xiàn)Api接口認(rèn)證
  • 基于Laravel Auth自定義接口API用戶認(rèn)證的實(shí)現(xiàn)方法
  • 詳解laravel安裝使用Passport(Api認(rèn)證)
  • laravel dingo API返回自定義錯(cuò)誤信息的實(shí)例
  • Laravel如何實(shí)現(xiàn)適合Api的異常處理響應(yīng)格式

標(biāo)簽:石嘴山 江門 駐馬店 深圳 內(nèi)江 大同 雙鴨山

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《在 Laravel 中動(dòng)態(tài)隱藏 API 字段的方法》,本文關(guān)鍵詞  在,Laravel,中,動(dòng)態(tài),隱藏,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《在 Laravel 中動(dòng)態(tài)隱藏 API 字段的方法》相關(guān)的同類信息!
  • 本頁(yè)收集關(guān)于在 Laravel 中動(dòng)態(tài)隱藏 API 字段的方法的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    主站蜘蛛池模板: 进贤县| 东平县| 五寨县| 冷水江市| 漳平市| 沈丘县| 江西省| 虹口区| 汪清县| 迭部县| 新津县| 延安市| 禹州市| 乌兰察布市| 瓦房店市| 社会| 清新县| 宁海县| 梁河县| 准格尔旗| 万载县| 威海市| 独山县| 自贡市| 阳信县| 张家口市| 洪江市| 泗水县| 汉源县| 宝应县| 平邑县| 墨江| 尚义县| 龙山县| 荔波县| 永定县| 会东县| 电白县| 眉山市| 静海县| 昌邑市|