Laravel How to display $hidden attribute on model on paginate
Another, possible easier solution depending on your requirements, is to call makeVisible
on the collection:
// Get all users
$users = User::with('role', 'level')->paginate(10)->makeVisible(['email']);
You can also use this with find
or get
:
$profile = auth()->user()->find($request->user()->id)->makeVisible(['email']);
I solve this using this method.
Users.php
on model
public function toArray()
{
// Only hide email if `guest` or not an `admin`
if (auth()->check() && auth()->user()->isAdmin()) {
$this->setAttributeVisibility();
}
return parent::toArray();
}
public function setAttributeVisibility()
{
$this->makeVisible(array_merge($this->fillable, $this->appends, ['enter_relationship_or_other_needed_data']));
}
and on controller just a simple
return User::with('role', 'level')->paginate(10);
I've read where pagination comes from toArray
before creating pagination. Thanks for all your help. Also helps