Created
September 26, 2017 19:23
-
-
Save deleugpn/965cc39f64536dbcc8c01fe69b8c7409 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment