Laravel - Serialization - Serializing To Json
To convert a model to JSON, you should use the toJson
method. Like toArray
, the toJson
method is recursive, so all attributes and relations will be converted to JSON. You may also specify any JSON encoding options that are supported by PHP:
use App\Models\User;
$user = User::find(1);
return $user->toJson();
return $user->toJson(JSON_PRETTY_PRINT);
Alternatively, you may cast a model or collection to a string, which will automatically call the toJson
method on the model or collection:
return (string) User::find(1);
Since models and collections are converted to JSON when cast to a string, you can return Eloquent objects directly from your application's routes or controllers. Laravel will automatically serialize your Eloquent models and collections to JSON when they are returned from routes or controllers:
Route::get('users', function () {
return User::all();
});