Answer the question
In order to leave comments, you need to log in
Why are hidden elements visible in JsonResource?
Laravel 5.6
Has a User model
It has
protected $hidden = [
'email'
];
public function toArray($request)
{
return [
'email' => $this->email, // email отображается
'email' => $this->resource->email, // email отображается
]
}
public function toArray($request)
{
$hidden = $this->resource->getHidden();
return [
'email' => in_array('email', $hidden) ? null : $this->resource->email, // email не отображается
]
}
Answer the question
In order to leave comments, you need to log in
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). $hidden
the 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;
}
}
return (new UserResource($model))->includeEmail();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question