How to convert Laravel collection array to json

Khirad Banu picture Khirad Banu · Sep 18, 2017 · Viewed 39.9k times · Source

How can i convert this Laravel collection array to json format like below.

//All records from users table.
$users = DB::table('users')->get();

// Required json format.
return '{
          "data": [

            {
              "DT_RowId": "row_1",
              "id": "Tiger",
              "clear": "Nixon",
              "fsssf": "System Architect",
              "tex": "[email protected]",
              "created_at": "Edinburgh",
              "updated_at": "Edinburgh"
            },
             {
              "DT_RowId": "row_2",
              "id": "Tiger",
              "clear": "Nixon",
              "fsssf": "System Architect",
              "tex": "[email protected]",
              "created_at": "Edinburgh",
              "updated_at": "Edinburgh"
            }

          ],
  "options": [],
  "files": []
}';

Sorry for the basic question,but i am unable to convert this into this jso.

Answer

Asim Shahzad picture Asim Shahzad · Sep 18, 2017

Have a look at the documentation.

You can use toJson(),to convert the collection to json object.

$users = DB::table('users')->get()->toJson();
dd($users);

You can also can do this in simple php way by using json_encode function

$users = json_encode($users);

Have a look at this link

Greetings and happy coding!