Recording data in array format to database workers column. I would then return this data in the appropriate JSON format. My problem is just getting the spname values from the nested array in the workers column and showing it in the datatables field view. My codes are as follows.
Api controller
public function apiZimmet() { /* test... ok it works $wdata=Zimmet::first(); $workers = json_decode($wdata->workers , true); foreach($workers as $key => $value) { echo $value['spname']."<br>"; } */ $data = Zimmet::with('proje:id,name'); return Datatables::eloquent($data) ->editColumn('workers', function ($data) { $workers = json_decode($data->workers , true); return $workers; }) ->addColumn('action', function ($data) { return '<ul class="header-dropdown m-r--5"> <li class="dropdown"> <a class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <i class="material-icons">more_vert</i> </a> <ul class="dropdown-menu pull-right"> <li> <a href="/system/stok-personeli/'.$data->id.'/edit" data-toggle="tooltip" data-original-title="Edit">Duzenle</a> </ul> </li> </ul>'; })->make(true); }
Return API file is below
"data":[ { "id":"12", "name":"test", "sicil_no":"1234", "proje_id":"1", "visible":0, "workers":[ { "spid":"1", "spsicil":"35678909", "spname":"ok" }, { "spid":"6", "spsicil":"123456", "spname":"sdsf sdfsdf" } ], "deleted_at":null, "created_at":"2020-04-02 23:29:23", "updated_at":"2020-04-02 23:29:23", "proje":{ "id":"1", "name":"deneme" }, "action":"edit" } ],
in view file ajax
ajax: { url: '{{route('api.zimmet')}}', method: 'POST' }, columns: [ {data: 'id', name: 'id', visible:false, searchable:false}, {data: 'name', name: 'name'}, {data: 'sicil_no', name: 'sicil_no'}, {data: 'proje.name', name: 'proje.name'}, {data: 'workers', name: 'workers'}, {data: 'action', name: 'action', orderable: false, searchable: false} ],
When I call the workers column here, gives [object Object],[object Object] error. What I want is to show the spname values in workers in the view file.
Best Regards
Advertisement
Answer
Because workers
is actually an array of objects, you will get exactly that (the object names) if you use data: 'workers'
.
Datatables has support for this situation, using its array bracket syntax. So, for example you can do this:
{data: 'workers[, ].spname', name: 'workers'},
Using your data, this will print out ok, sdsf sdfsdf
in the table cell. It iterates through all the spname
items, and separates them with a comma followed by a space.
If you want something more elaborate, you may need to pre-process your JSON – for example, to flatten it. But the above may be sufficient for your needs.