Skip to content

Instantly share code, notes, and snippets.

@deleugpn
Last active November 23, 2018 02:59
Show Gist options
  • Save deleugpn/f100ba7d474366410a44aeff83c52958 to your computer and use it in GitHub Desktop.
Save deleugpn/f100ba7d474366410a44aeff83c52958 to your computer and use it in GitHub Desktop.
Filter resource fields by query string
<?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)
{
if ($request->fields) {
// Delegate to a separate method to keep it clean and readable.
return $this->processRequestedFields($request->fields);
}
// Since we're using early-return inside the if statement, there's no need for an else.
return parent::toArray($request);
}
/**
* Filter the resource with the provided fields.
*
* @param string $fields
* @return array
*/
protected function processRequestedFields($fields)
{
$attributes = $this->resource->getAttributes();
$requestedFields = explode(',', $fields);
return collect($attributes)->only($requestedFields);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment