nscherneck's avatar

toJson gives no key

Hey all,

I'm trying to create a dynamic select in an HTML form by way of AJAX.

Here's the javascript from the HTML page...

<script>

function fetch_select(val)
{

 $.ajax({
 type: 'post',
 url: '/update_model_select',
 data: {
  manufacturer_id:val
 },
 dataType: "json",
// success: function (data) {
//     console.log(data);
// }
 success: function (data) {
  document.getElementById("model").innerHTML="<option value=\"" + data.id + "\">" + data.model + "</option>";
 }
 });
}

</script>

My route...

Route::post('update_model_select', 'ComponentsController@update_model_select');

ComponentsController...

  public function update_model_select(Request $request) {
    $manufacturer = Manufacturer::find($request->manufacturer_id);
    $components = $manufacturer->components->pluck('id', 'model');
    return $components->toJson();
  }

Problem is that I'm not getting the JSON format I was expecting. Here's a sample of the data output from the console...

{VLF-250: 6, VLF-500: 7, VLC-RO: 8}
VLC-RO
:
8
VLF-250
:
6
VLF-500
:
7

I'm not sure how to iterate this out without they keys. Is it possible to return the keys as well?

0 likes
3 replies
WebKenth's avatar
WebKenth
Best Answer
Level 16

This should fix it

return $components->all();

The reason you are not returning a JSON array is because when you ->pluck() something it returns a collection rather than an array

So you need to call some form of getter to turn it into a regular array.

And as a bonus, when you return an array via Ajax requests Laravel automatically turns it into JSON so there's no need to call ->toJson()

1 like
nscherneck's avatar

Quick response..thank you. Tried this and ended up with the same output as before...

{VLF-250: 6, VLF-500: 7, VLC-RO: 8}
VLC-RO
:
8
VLF-250
:
6
VLF-500
:
7
nscherneck's avatar

Great, that did it. I'll just filter out columns in the model . Thank you!

Please or to participate in this conversation.