Laravel How to display $hidden attribute on model on paginate
When building an API or a dashboard, it is common to define a list of attributes that should remain hidden from the JSON response for security or cleanliness reasons. In Laravel 5.5 and later, the standard way to enforce this at the application level is using the makeHidden method within your controller or service layer. You might have a $hidden array defined like this:
$hidden = ['password', 'remember_token', 'email'];
If you are fetching a single resource, such as a user profile for the authenticated person, applying visibility rules is straightforward. You can retrieve the model and explicitly make specific attributes visible using makeVisible:
$profile = auth()->user()->find($request->user()->id);
$profile->makeVisible(['email']);
return response()->json($profile);
This approach works because you are manipulating the Eloquent model instance directly before serializing it to JSON. However, problems arise when you attempt to apply these visibility rules inside a query chain that includes pagination, specifically using paginate().
Consider the scenario where you need to return a paginated list of all users, including their roles and levels, but you only want to expose the email field for this specific endpoint. A common mistake is chaining makeVisible directly onto the Query Builder instance before calling paginate():
// Get all users
$users = User::with('role', 'level')->makeVisible(['email'])->paginate(10); // Doesn't work
This pattern fails because makeVisible is a method designed for model instances, not query builders. When you call it on the builder, Laravel ignores it or throws an error depending on your version, and the resulting collection returned by paginate() retains the hidden attributes as defined in your global settings or ignores the visibility change entirely.
To solve this, you must separate the retrieval logic from the serialization logic. The most reliable method is to fetch the paginated results as a standard collection first, then apply the visibility rules to that collection object. Since paginate returns a LengthAwarePaginator, which extends Collection, you can call makeVisible on the paginator instance itself.
Here is the corrected implementation:
$users = User::with('role', 'level')->paginate(10);
$users->makeVisible(['email']);
return response()->json($users);
By calling makeVisible after paginate, you ensure that the transformation happens on the collection of models before the JSON response is generated. This preserves your relationship loading (with('role', 'level')) while selectively exposing the sensitive or restricted fields like email.
It is important to note that this approach applies the visibility rules globally for that specific request instance. If you have a strict $hidden array defined in your model, remember that makeVisible overrides those defaults for the duration of the response. Conversely, if you need to hide additional attributes beyond the base $hidden, you would use makeHidden after fetching, ensuring the order matters: hidden by default, then selectively shown or hidden as needed.
While Laracasts discussions suggest using custom JSON serialization traits or dynamic methods, these often add complexity that isn't necessary for simple visibility toggling. The direct manipulation of the paginator instance is efficient and leverages Laravel's built-in Eloquent capabilities without requiring extra packages or complex trait implementations. This keeps your codebase clean and adheres to the principle of least surprise when handling data serialization in paginated responses.