I’m needing to filter a collection based on a defined policy. But get nothing back, can someone point me in the right direction.
Perhaps it’s possible to do the check in the controller. However, it seems logical to do it in the API Resource. As I understand it, the whole point of the API Resource is to serve a model OR a collection of models in custom & tailored way.
<code><?php
namespace AppHttpResources;
use IlluminateHttpRequest;
use IlluminateHttpResourcesJsonJsonResource;
use IlluminateSupportFacadesAuth;
class UserResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'name' => $this->name,
'email' => $this->email,
'client_id' => $this->client->id,
'role' => $this->role->name,
'accessible_projects' => $this->client->projects->filter(function ($item)
{
Auth::user()->can('view', $item);
}
),
];
}
}
</code>
<code><?php
namespace AppHttpResources;
use IlluminateHttpRequest;
use IlluminateHttpResourcesJsonJsonResource;
use IlluminateSupportFacadesAuth;
class UserResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'name' => $this->name,
'email' => $this->email,
'client_id' => $this->client->id,
'role' => $this->role->name,
'accessible_projects' => $this->client->projects->filter(function ($item)
{
Auth::user()->can('view', $item);
}
),
];
}
}
</code>
<?php
namespace AppHttpResources;
use IlluminateHttpRequest;
use IlluminateHttpResourcesJsonJsonResource;
use IlluminateSupportFacadesAuth;
class UserResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'name' => $this->name,
'email' => $this->email,
'client_id' => $this->client->id,
'role' => $this->role->name,
'accessible_projects' => $this->client->projects->filter(function ($item)
{
Auth::user()->can('view', $item);
}
),
];
}
}
New contributor
DiTrain is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.