A
A
Artem00712018-09-22 12:56:25
Laravel
Artem0071, 2018-09-22 12:56:25

Why are hidden elements visible in JsonResource?

Laravel 5.6
Has a User model
It has

protected $hidden = [
        'email'
    ];

So, I created UserResource (for API):
public function toArray($request)
{
  return [
     'email' => $this->email, // email отображается
     'email' => $this->resource->email, // email отображается
  ]
}

I had to do the following:
public function toArray($request)
{
  $hidden = $this->resource->getHidden();
  return [
     'email' => in_array('email', $hidden) ? null : $this->resource->email, // email не отображается
  ]
}

That is, laravel knows that this is a hidden field, but it still shows it
. Maybe I'm getting the parameter wrong somehow?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Wells, 2018-09-26
@Alex_Wells

Because you access it through a magic getter on the resource object ( $this->email), which in turn simply pulls the same field on the resource (model). $hiddenthe model hides the field only when ->toArray(), but it is still in the attributes.
Everything is logical and should work this way) Outputs:
1) remove from the resource 2) do'email' => $this->email

class UserResource {
    private $includeEmail = false;

    public function toArray($request) {
        return [
            'email' => $this->when($this->includeEmail, $this->email)
        ];
    }

    public function includeEmail() {
        $this->includeEmail = true;

        return $this;
    }
}

And later do in the controller. return (new UserResource($model))->includeEmail();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question