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 JSON encoding options supported by PHP:
For Example(1)
1.Create route in web.php file
Route::get('/SerializationToJSON', 'demoController@SerializationToJSON')->name('SerializationToJSON');
2.Create demoController by using below command
php artisan make:controller demoController
3.Implement code in demo controller as below
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use App\User;
class demoController extends AppBaseController
{
public function SerializationToJSON()
{
$user = User::find(1);
// return $user->toJson();
return $user->toJson(JSON_PRETTY_PRINT);
}
}toJson
method on the model or collection:
$user = App\User::find(1);
return (string) $user;
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:
Route::get('users', function () {
return App\User::all();
});
Relationships