欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

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.

    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

    $users = json_decode($users);

    Have a look at this link

    Greetings and happy coding!

    return Response::json([
        'data' => $value
    ], 200); 

    hope this helps!

    if we you laravel 5.5 then you should use eloquent-resources

    Couple of things you can do, you can use default method ->toJson() with the user collection like this

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

    If you do have troubles with it them you can php build in json_encode method here is the full documentation http://php.net/manual/en/function.json-encode.php

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

    Hope this helps!

    If you are looking into doing if for a blade template you can use @json

    like so

    <script type="text/javascript">
        var PARAMS = @json($params)
    </script>

    P.S.Tested in Laravel 5.6

    来自  https://stackoverflow.com/questions/46274135/how-to-convert-laravel-collection-array-to-json

    普通分类: