How to index count from json in Laravel

女生的网名这么多〃 提交于 2020-03-25 12:31:32

问题


I have a messages table with Structure as follows:

  • id sender_id receiver_id pet_id description

the description is the text message. I am fetching messages of users related to a specific pet by fetching all messages where the sender is user or receiver is user and then filtering them by petId I want.

function messagesByPet($petId,$userId){
  $messages = Message::where('sender_id',$userId)->orWhere('receiver_id',$userId)->orderBy('created_at','asc')->get();
  $message = $messages->where('pet_id', $petId);
  return $message;
}

The above function works but the JSON I receive is as follows. I don't want indexes in it such as "0" "3". How to remove them?

{
  "0": {
    "id": 197,
    "sender_id": "5718",
    "receiver_id": "5716",
    "pet_id": "5113",
    "description": "Hi",
    "created_at": "2020-03-16 05:29:41",
    "updated_at": "2020-03-16 05:29:41"
  },
  "3": {
    "id": 203,
    "sender_id": "5718",
    "receiver_id": "5716",
    "pet_id": "5113",
    "description": "Hi",
    "created_at": "2020-03-18 22:06:40",
    "updated_at": "2020-03-18 22:06:40"
  }
}

回答1:


After get() method , you got the collection. So you can use values() method to returns a new collection with the keys reset to consecutive integers:

return $message->values();


来源:https://stackoverflow.com/questions/60748842/how-to-index-count-from-json-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!