Serialize model data into arrays or JSON
brief introduction
Serialization Model&Collection
Serialized as an array
$user = App\User::with('roles')->first(); return $user->toArray();
$users = App\User::all(); return $users->toArray();
Serialized as JSON
$user = App\User::find(1); return $user->toJson();
$user = App\User::find(1); return (string) $user;
Route::get('users',function(){ return App\User::all(); });
Hide attributes in JSON
<? php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { /** *Properties hidden in the array * * @var array */ protected $hidden = ['password']; }
Note: If you want to hide the association, use the method name of the association instead of the dynamic attribute name.
<? php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { /** *Properties displayed in the array * * @var array */ protected $visible = ['first_name', 'last_name']; }
return $user->makeVisible('attribute')->toArray();
return $user->makeHidden('attribute')->toArray();
Append value to JSON
<? php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { /** *Get administrator ID for user * * @return bool */ public function getIsAdminAttribute() { return $this->attributes['admin'] == 'yes'; } }
<? php namespace App; use Illuminate\Database\Eloquent\Model; class User extends Model { /** *Accessor appended to model array form * * @var array */ protected $appends = ['is_admin']; }
return $user->append('is_admin')->toArray(); return $user->setAppends(['is_admin'])->toArray();
Date Serialization
<? php namespace App\Providers; use Illuminate\Support\Carbon; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Perform post-registration booting of services. * * @return void */ public function boot() { Carbon::serializeUsing(function ($carbon) { return $carbon->format('U'); }); } /** * Register bindings in the container. * * @return void */ public function register() { // } }