Laravel - Serialization - Serializing To Arrays
To convert a model and its loaded relationships to an array, you should use the toArray
method. This method is recursive, so all attributes and all relations (including the relations of relations) will be converted to arrays:
use App\Models\User;
$user = User::with('roles')->first();
return $user->toArray();
The attributesToArray
method may be used to convert a model's attributes to an array but not its relationships:
$user = User::first();
return $user->attributesToArray();
You may also convert entire collections of models to arrays by calling the toArray
method on the collection instance:
$users = User::all();
return $users->toArray();