Last active
November 23, 2018 02:59
-
-
Save deleugpn/f100ba7d474366410a44aeff83c52958 to your computer and use it in GitHub Desktop.
Filter resource fields by query string
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 | |
{ | |
/** | |
* 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