How to convert Laravel collection array to json

Viewed 54351

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.

6 Answers

If you are looking into doing if for a blade template you can use the @json Blade directive, like so:

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

P.S.Tested in Laravel 5.6

in Laravel you can easily serialize your php object like so :

public static function getLocataireByCin($cin)
    {
        return Locataire::where('cin', $cin)
            ->first()
            ->toJson(JSON_PRETTY_PRINT);
    }

and then retrieve it on your frontEnd (using js/jquery for example ) :

$("#cinLocataire").keyup(function () {
        $.ajax({
            url: "{{ route('Caisse.store') }}",
            type: "POST",
            data: {
                cin: $(this).val()
            },
            success: function (locataireData) {
                var locataire = JSON.parse(locataireData); // <-- here
                console.log(
                    locataire.nom
                );
            },
        })
    });
Related