Member-only story
Laravel Eloquent Serialization: Hidden, Appends, Dates
The easiest Laravel API is one line: return User::all();. Eloquent turns the models into JSON for you. That convenience is also where leaks and slow endpoints start: a password hash in the response, a date in a format your frontend does not expect, or an "extra" computed field that quietly fires a query per row. This article walks through how Eloquent serialization works in Laravel 13, using the official documentation as the map and a real database to test the parts that surprise people.
The basics: toArray() and toJson()
$user = User::with('roles')->first();
$user->toArray(); // attributes + loaded relationships, recursively
$user->attributesToArray(); // attributes only, no relationships
$user->toJson(); // JSON string
$user->toJson(JSON_PRETTY_PRINT);
(string) $user; // same as toJson()I confirmed that casting a model to a string produced exactly the same text as toJson(). According to the docs, models and collections returned from a route or controller are converted to JSON automatically. I did not run a real route, so that part is from the documentation.
One detail that trips people up: a loaded relationship appears in the output under a snake_case key even though the method is camelCase. My blogPosts()…









