Repository navigation
How do I add visible/hide methods to a Resource? #50672
Replies: 1 comment
|
You can implement that fluent API in a shared resource base class, filtering the resolved resource array rather than changing the underlying model's visibility: namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Arr;
abstract class SelectableResource extends JsonResource
{
protected ?array $selectedFields = null;
protected array $excludedFields = [];
public function visible(array|string $fields): static
{
$this->selectedFields = (array) $fields;
return $this;
}
public function hidden(array|string $fields): static
{
$this->excludedFields = (array) $fields;
return $this;
}
public function resolve($request = null): array
{
$data = parent::resolve($request);
if ($this->selectedFields !== null) {
$data = Arr::only($data, $this->selectedFields);
}
return Arr::except($data, $this->excludedFields);
}
}Then make Your examples become: NumberResource::make($number)->visible(['id', 'number']);
NumberResource::make($number)->visible('id');
NumberResource::make($number)->hidden(['id', 'number']);Calling With this implementation:
Keep authorization-sensitive conditions inside the resource itself; this field selector should only narrow what the resource is already allowed to expose. Reference: [Laravel API Resources](https://laravel.com/docs/12.x/eloquent-resources). |
Uh oh!
There was an error while loading. Please reload this page.
Hi! I need to make sure that when calling:
visible(['id', 'name'])orvisible('id')- I was only asked for keys with values for how toArray works($request)hidden(['id', 'name'])orhidden('id')is also a method in several places that opens due to the use of a key with values.The proposed syntax came across like this:
All reactions