Serialization


Serialize to array

  • Serialize to JSON
  • ##Hide JSON properties
    • Append JSON value
    • Serialized date
  • Introduction
  • When building a JSON API, you often need to convert models and relationships into arrays or JSON. For these operations, Eloquent provides some convenient methods and property control in serialization.

##Serialized Models & Collections

##

Serialize to array

To convert the model and its loaded association into an array, you can use the toArray method. This is a recursive method, so all attributes and associations (including associated associations) will be converted into arrays:

$user = App\User::with('roles')->first();return $user->toArray();

You can also convert the entire model collection into an array:

$users = App\User::all();return $users->toArray();

Serialize to JSON

MethodtoJson can convert the model into JSON. Like the method toArray, the toJson method is recursive, so all properties and relationships are converted to JSON. You can also specify JSON encoding options supported by PHP. :

$user = App\User::find(1);
return $user->toJson();
return $user->toJson(JSON_PRETTY_PRINT);

You can also convert the model or collection into a string. The method toJson will automatically call:

$user = App\User::find(1);
return (string) $user;

Since the model and collection will be converted into a string Convert to JSON, so the Eloquent object can be returned directly in the application's route or controller:

Route::get('users', function () {
    return App\User::all();
  });

##Hide JSON attributes

Sometimes you want to hide certain attributes in the model array or JSON, such as passwords, you can add the

$hidden attribute to the model:

<?php
    namespace App;
    use Illuminate\Database\Eloquent\Model;
    class User extends Model{    
    /**
     * 数组中的属性会被隐藏。
     *
     * @var array
     */  
     protected $hidden = ['password'];
   }

{note} When hiding an association, you need to use the associated method name.

In addition, you can also use the attribute

$visible to define an array of models and a whitelist visible to JSON. No other attributes will appear in the converted array or JSON:

<?phpnamespace App;
    use Illuminate\Database\Eloquent\Model;
    class User extends Model{   
     /**
     * 数组中的属性会被展示。
     *
     * @var array
     */  
     protected $visible = ['first_name', 'last_name'];
   }

Temporarily modify the visible attributes

If you need to display hidden attributes in a model instance, you can Use the

makeVisible method. Method makeVisible Returns the model instance:

return $user->makeVisible('attribute')->toArray();

Correspondingly, if you need to hide visible properties in a model instance, you can use the

makeHidden method.

return $user->makeHidden('attribute')->toArray();

Append JSON value

Sometimes, you need to add some attributes to the array or JSON that the database does not have corresponding fields. . To implement this function, first define an accessor for it:

<?php
    namespace App;
    use Illuminate\Database\Eloquent\Model;
    class User extends Model{    
    /**
     * 为用户获取管理员标识。
     *
     * @return bool
     */   
     public function getIsAdminAttribute()  
       {      
         return $this->attributes['admin'] == 'yes';  
       }
    }

Then, add the attribute name to the model attribute

appends. Note that although accessors are defined using camelCase, property names are usually referenced using SnakeCase.

<?php
    namespace App;
    use Illuminate\Database\Eloquent\Model;
    class User extends Model{    
    /**
     * 追加到模型数组表单的访问器。
     *
     * @var array
     */   
    protected $appends = ['is_admin'];
  }

After you append a property using the

append method, it will be included in the model's array and JSON. appends Properties in the array will also respect the visible and hidden settings configured on the model.

Run-time appending

On a single model instance, use method

append to append properties, or, use method setAppends Overwrite the entire array of appended attributes:

return $user->append('is_admin')->toArray();
return $user->setAppends(['is_admin'])->toArray();

Serialized date

Customize the date format of any attribute

You can customize the date format separately for the date attribute in Eloquent's attribute type conversion:

protected $casts = [
    'birthday' => 'date:Y-m-d',    
    'joined_at' => 'datetime:Y-m-d H:00',
  ];

Carbon Global Customization

Laravel extends the Carbon date library which facilitates Carbon's JSON serialization. To customize the serialization of all Carbon dates throughout your application, you can use the Carbon::serializeUsing method. Method serializeUsing accepts a closure that returns a date as a string.

<?php
    namespace App\Providers;
    use Illuminate\Support\Carbon;
    use Illuminate\Support\ServiceProvider;
    class AppServiceProvider extends ServiceProvider{   
     /**
     * 执行注册后,启动服务
     *
     * @return void
     */    
     public function boot()  
       {     
          Carbon::serializeUsing(function ($carbon) {   
                   return $carbon->format('U');       
                 });   
          }   
     /**
     * 在服务容器中注册绑定
     *
     * @return void
     */   
     public function register()  
       {      
         //   
        }
     }
This article was first published on the LearnKu.com website.