I know that to hide columns, we can use the protected $hidden
attribute, however it will hide for everyone who will request the data.
For example, I have route / faq / index, a table / model with questions and answers (FAQ) and want to hide the updated_by
and created_by
fields so that non-authenticated users can see, does Laravel have any resource for this type of situation?
You could use Eloquent Resources . Then you can conditionally return attributes like this:
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'secret' => $this->when(Auth::check(), 'secret-value'), // this field will only be visible when the users is authed
];
}
You can also group the hidden attributes:
$this->mergeWhen(Auth::check(), [
'first-secret' => 'value',
'second-secret' => 'value',
]),
Read about conditional attributes here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.