Menu

Laravel Eloquent Serialization: Hidden, Appends, Dates
📰

Laravel Eloquent Serialization: Hidden, Appends, Dates

DEV Community: laravel·devTalk·3 days ago
#z1opWtlZ
#devtolaravel#devto#dev#user#hidden
Reading 0:00
15s threshold

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()

Enter fullscreen mode

Exit fullscreen mode

I confirmed that casting a model to a string produced exactly the same text as toJson() .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.