Laravel 12 Eloquent Serialization: A Complete Beginner’s Guide

Author

Kritim Yantra

Apr 20, 2025

Laravel 12 Eloquent Serialization: A Complete Beginner’s Guide

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:

  • What Eloquent serialization is and why it’s useful
  • Default serialization behavior in Laravel
  • How to customize JSON output using API Resources and Serialization Casts
  • Hiding sensitive fields and appending computed attributes
  • Best practices for efficient serialization

By the end, you’ll understand how to control and optimize data serialization in Laravel 12.


What is Eloquent Serialization?

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.

Why is Serialization Important?

  1. API Development – When building RESTful APIs, you often return JSON responses.
  2. Security – Hide sensitive fields (e.g., passwords, API keys) from responses.
  3. Data Transformation – Modify data structure before sending it to the client.
  4. Performance Optimization – Control which fields are loaded to reduce payload size.

Default Serialization in Laravel

By default, when you return an Eloquent model in a route, Laravel automatically serializes it to JSON.

Example: Basic Serialization

// 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.


Customizing Serialization

Sometimes, you need more control over the output. Laravel provides multiple ways to customize serialization.

1. Hiding Attributes (Sensitive Data)

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.

2. Making Temporary Visible Fields

If you want to temporarily include hidden fields:

$user = User::find(1);
return $user->makeVisible('password')->toArray();

3. Appending Computed Attributes

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.


Using API Resources for Advanced Serialization

For full control over JSON structure, Laravel provides API Resources, which act like transformers.

Step 1: Create a Resource

php artisan make:resource UserResource

This generates app/Http/Resources/UserResource.php.

Step 2: Define the Resource Structure

// 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'),
    ];
}

Step 3: Use the Resource in a Controller

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"
}

Collections (Multiple Models)

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

Custom Casts & Serialization

Laravel allows custom casts to modify how attributes are serialized.

Example: JSON Casting

If a database field stores JSON:

// app/Models/User.php
protected $casts = [
    'preferences' => 'json',
];

Now, preferences will be automatically encoded/decoded.

Custom Cast Classes

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,
];

Conditional Serialization

Sometimes, you want to include fields only under certain conditions.

Using 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.


Best Practices for Eloquent Serialization

  1. Use API Resources for APIs – Provides clean separation of concerns.
  2. Hide Sensitive Data – Always exclude passwords, tokens, etc.
  3. Optimize Performance – Use select() to load only needed fields.
  4. Leverage Caching – Cache serialized responses if data doesn’t change often.
  5. Keep JSON Structure Consistent – Follow a standard format (e.g., JSON:API).

Conclusion

Eloquent serialization in Laravel 12 gives you full control over how your data is presented in APIs and responses. Key takeaways:

  • Use $hidden and $appends for simple field control.
  • API Resources provide powerful JSON customization.
  • Custom casts help format complex data types.
  • Always secure sensitive data before serializing.

By mastering these techniques, you can build efficient, secure, and well-structured APIs in Laravel.

Happy coding!

Tags

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Sign in with Google

Related Posts