Dom
Dom

Reputation: 3444

How to simplify this Laravel resource?

I use Laravel 7.

I build some apis in which the "GET" result depends on the request. For example

/schools?fields=name,id,school_type_id

means "give me all the schools, but only the name + id + school_type_id".

/schools?

means "give me all the schools, all the columns".

To do that I am using a resource :

class SchoolResource extends JsonResource
{
    public function toArray($request)
    {
        $fields = $request->has('fields') ? explode(',', $request->fields) : [];

        return [
            'id' => $this->when(0 === \count($fields) || \in_array('id', $fields, true), $this->id),
            'name' => $this->when(0 === \count($fields) || \in_array('name', $fields, true), $this->name),
            .......
        ]

It works fine, but I think it is complicated (and also not "elegant"). Is it possible to simplify that?

Upvotes: 0

Views: 51

Answers (1)

Robbin Benard
Robbin Benard

Reputation: 1652

use Illuminate\Support\Arr;

class SchoolResource extends JsonResource
{
    public function toArray($request)
    {
        $fields = $request->has('fields') ? explode(',', $request->fields) : [];

        return Arr::only($this->resource->toArray(), $fields);
    }
}

Upvotes: 1

Related Questions