Laravel Eloquent: Serializing Models and Collections to Arrays and JSON, Hiding Attributes, Appending Values, and Custom Date Formats
This guide explains how Laravel Eloquent can serialize models and their relationships to arrays or JSON, control visible and hidden attributes, append custom values, and customize date formatting using casts and Carbon serialization, with practical code examples for each feature.
Serializing Models & Collections
To convert a model and its loaded relationships to an array, use the toArray method, which recursively includes all attributes and nested relations.
$user = App\User::with('roles')->first();
return $user->toArray();You can also convert an entire collection to an array:
$users = App\User::all();
return $users->toArray();Serializing to JSON
The toJson method converts a model to JSON and works like toArray but returns a JSON string. The method is recursive, so all attributes and relations are included.
$user = App\User::find(1);
return $user->toJson();When a model or collection is cast to a string, Laravel automatically calls toJson:
$user = App\User::find(1);
return (string) $user;Because of this behavior, you can return an Eloquent object directly from a route or controller:
Route::get('users', function () {
return App\User::all();
});Hiding JSON Attributes
To hide certain attributes (e.g., passwords) from the serialized output, define a $hidden property on the model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Attributes that should be hidden
*
* @var array
*/
protected $hidden = ['password'];
}{note} To hide relationships, use the relationship method name.
Alternatively, you can define a whitelist of visible attributes with $visible:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Attributes that should be visible
*
* @var array
*/
protected $visible = ['first_name', 'last_name'];
}Temporarily Modifying Visibility
Use makeVisible to temporarily expose hidden attributes, returning a model instance:
return $user->makeVisible('attribute')->toArray();Use makeHidden to temporarily hide visible attributes:
return $user->makeHidden('attribute')->toArray();Appending JSON Values
To add computed attributes that do not exist in the database, define an accessor and list the attribute name in the $appends array:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get admin flag for the user
*
* @return bool
*/
public function getIsAdminAttribute()
{
return $this->attributes['admin'] == 'yes';
}
}Then add the accessor name (snake_case) to $appends:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Attributes to append to the model's array form
*
* @var array
*/
protected $appends = ['is_admin'];
}At runtime you can also append attributes on a single model instance using append or replace the entire list with setAppends:
return $user->append('is_admin')->toArray();
return $user->setAppends(['is_admin'])->toArray();Serializing Dates
Custom Date Formats for Specific Attributes
Define custom formats for date attributes in the model's $casts array:
protected $casts = [
'birthday' => 'date:Y-m-d',
'joined_at' => 'datetime:Y-m-d H:00',
];Global Carbon Serialization
Laravel extends the Carbon library; you can globally customize how Carbon dates are serialized by using Carbon::serializeUsing in a service provider:
<?php
namespace App\Providers;
use Illuminate\Support\Carbon;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Carbon::serializeUsing(function ($carbon) {
return $carbon->format('U');
});
}
public function register()
{
//
}
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
