Kritim Yantra
Apr 20, 2025
Introduction
When building APIs or handling data in Laravel, you often need to convert Eloquent models into JSON or arrays. This process is called serialization, and Laravel provides powerful tools to customize how your data is structured when sent to the frontend or external services.
In this guide, we’ll cover:
By the end, you’ll understand how to control and optimize data serialization in Laravel 12.
Serialization is the process of converting an Eloquent model into a format like JSON or an array, making it easy to send data to APIs, JavaScript applications, or other services.
By default, when you return an Eloquent model in a route, Laravel automatically serializes it to JSON.
// routes/api.php
Route::get('/user/{id}', function ($id) {
return User::find($id);
});
Output (JSON):
{
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"created_at": "2024-01-01T12:00:00.000000Z",
"updated_at": "2024-01-01T12:00:00.000000Z"
}
Laravel includes all visible attributes by default.
Sometimes, you need more control over the output. Laravel provides multiple ways to customize serialization.
To exclude fields (e.g., passwords), use the $hidden
property in the model:
// app/Models/User.php
protected $hidden = ['password', 'remember_token'];
Now, these fields won’t appear in JSON responses.
If you want to temporarily include hidden fields:
$user = User::find(1);
return $user->makeVisible('password')->toArray();
To include accessor methods (e.g., full_name
), use $appends
:
// app/Models/User.php
protected $appends = ['full_name'];
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
Now, full_name
will appear in the JSON response.
For full control over JSON structure, Laravel provides API Resources, which act like transformers.
php artisan make:resource UserResource
This generates app/Http/Resources/UserResource.php
.
// app/Http/Resources/UserResource.php
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'registered_at' => $this->created_at->format('Y-m-d'),
];
}
use App\Http\Resources\UserResource;
Route::get('/user/{id}', function ($id) {
return new UserResource(User::find($id));
});
Output:
{
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"registered_at": "2024-01-01"
}
To format multiple users:
php artisan make:resource UserCollection
// app/Http/Resources/UserCollection.php
public function toArray($request)
{
return [
'data' => $this->collection,
'links' => [
'self' => url('/users'),
],
];
}
Usage:
return new UserCollection(User::all());
Laravel allows custom casts to modify how attributes are serialized.
If a database field stores JSON:
// app/Models/User.php
protected $casts = [
'preferences' => 'json',
];
Now, preferences
will be automatically encoded/decoded.
For advanced serialization, create a custom cast:
php artisan make:cast JsonCast
// app/Casts/JsonCast.php
public function get($model, $key, $value, $attributes)
{
return json_decode($value, true);
}
public function set($model, $key, $value, $attributes)
{
return json_encode($value);
}
Usage in Model:
protected $casts = [
'metadata' => JsonCast::class,
];
Sometimes, you want to include fields only under certain conditions.
when()
in API Resources// UserResource.php
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->when($request->user()->isAdmin(), $this->email),
];
}
Now, email
is only included for admin users.
select()
to load only needed fields.Eloquent serialization in Laravel 12 gives you full control over how your data is presented in APIs and responses. Key takeaways:
$hidden
and $appends
for simple field control.By mastering these techniques, you can build efficient, secure, and well-structured APIs in Laravel.
Happy coding!
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google