Search code examples
jsonlaravel-5laravel-collection

How to convert Laravel collection array to json


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": "t.nixon@datatables.net",
              "created_at": "Edinburgh",
              "updated_at": "Edinburgh"
            },
             {
              "DT_RowId": "row_2",
              "id": "Tiger",
              "clear": "Nixon",
              "fsssf": "System Architect",
              "tex": "t.nixon@datatables.net",
              "created_at": "Edinburgh",
              "updated_at": "Edinburgh"
            }

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

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


Solution

  • 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!