Skip to content

Instantly share code, notes, and snippets.

@deleugpn
Created September 26, 2017 19:23
Show Gist options
  • Select an option

  • Save deleugpn/965cc39f64536dbcc8c01fe69b8c7409 to your computer and use it in GitHub Desktop.

Select an option

Save deleugpn/965cc39f64536dbcc8c01fe69b8c7409 to your computer and use it in GitHub Desktop.
<?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