Q:

How to hide fields for unauthenticated users with Laravel?

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?

A:

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.

