问题
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