Hello everyone actually I'm using laravel API and I'm trying to get this response:
chatsContacts: Array(2)
0:
about: "Cake pie jelly jelly beans. Marzipan lemon drops halvah cake. Pudding cookie lemon drops icing"
avatar: "/static/media/avatar-s-2.d21f2121.jpg"
chat:
id: 1
lastMessage:
message: "If it takes long you can mail me at my mail address."
senderId: 11
time: "2022-06-05T22:55:42.271Z"
[[Prototype]]: Object
unseenMsgs: 0
[[Prototype]]: Object
fullName: "Felecia Rower"
id: 1
role: "Frontend Developer"
status: "offline"
as what you are seeing the chat is inside chatsContacts and the lastMessage is inside chat.
I did an attempt to get this response but I get : ErrorException: Attempt to assign property 'lastMessage' of non-object
this is the code:
function listChats($id){
$types= chat::all()->where('userId', $id);
$c= chat::all()->where('userId', $id);
$d= chat::all()->where('userId', $id);
foreach ($types as $chats) {
$chats->chatsContacts = chat::all()->where('userId', $chats->userId);
}
foreach ($c as $chats) {
$chats->chat = DB::table('chats')->where('id', $chats->id)->get();
foreach ($chats as $m) {
$m->lastMessage = DB::table('chats')->select('message','time','senderId')->orderBy('time', 'asc')
->skip(0)->take(1)->get();
}}
foreach ($d as $chats) {
$chats->profileUser = chat::all()->where('userId', $chats->userId); ;
}
return ['chatsContacts' => $types, 'contacts' => $c, 'profileUser' => $d];
}
I would be veryyy thankful if I get a push to resolve this issue
CodePudding user response:
foreach ($chats as $m) {
$m->lastMessage = DB::table('chats')->select('message','time','senderId')->orderBy('time', 'asc')
->skip(0)->take(1)->get();
}}
what is $chats in this line?? maybe this is the reason you get error?
i suggest you to combine you data after all the foreach done.
like this
$responsedata['whatever'] = $yourdata
$responsedata['whatever2'] = $yourdata2
then you can return $responsedata
CodePudding user response:
Because ::all()
returns array not object. Try to change
$types= chat::where('userId', $id)->get();