I am currently writing a chat application. So far users can send each other messages and I am able to store the messages in my database. Now I want to show the messages which are stored in the database in my onOpen function, when the user opens up the page to message another user.
This is what my onOpen function looks like:
public function onOpen(ConnectionInterface $conn)
{
$query = $conn->httpRequest->getUri()->getQuery();
preg_match_all('!\d+!', $query, $matches);
$my_id = $matches[0][0];
$friend_id = $matches[0][1];
$conn->resourceId = $my_id;
$this->users[$conn->resourceId] = $conn;
$messages = Private_message::where([
['user1',$my_id],
['user2',$friend_id]
])->orWhere([
['user1',$friend_id],
['user2',$my_id]
])->get()->toArray();
}
I want to return the $messages
array to my privateChat.blade.php
view so I can print them out.
Iv'e tried to do return view('privateChat',['messages' => $messages]);
and @dd($messages)
in my privateChat.blade.php
but it says the variable is undefined.
I also tried return $messages
and print them out in my onopen js function but it doesn't work. What is the right way to this?
as you can see you are not returning anything back to view
so
public function onOpen(ConnectionInterface $conn)
{
$query = $conn->httpRequest->getUri()->getQuery();
preg_match_all('!\d+!', $query, $matches);
$my_id = $matches[0][0];
$friend_id = $matches[0][1];
$conn->resourceId = $my_id;
$this->users[$conn->resourceId] = $conn;
$messages = Private_message::where([
['user1',$my_id],
['user2',$friend_id]
])->orWhere([
['user1',$friend_id],
['user2',$my_id]
])->get()->toArray();
$viewShareVariables = compact('messages');
return view('privateChat',$viewShareVariables);
}
If any issues kindly comment below