我在我网站上的用户之间使用简单的消息系统。
每条消息都有自己的unique ID
soo,每个用户只能看到当前消息中的title
和text
。我现在不希望代码聊天消息系统只想显示表中2个用户之间当前消息上方的所有消息。
示例我的消息现在的样子:
Title:
Text/Message:
Reply Button
我希望现在显示在所有其他消息之上。
默认代码:
Message from <span class="font-weight-600">{{$message->From->username}}</span> sent to <span class="font-weight-600">{{$message->To->username}}</span>
<div align="middle" class="form-group">
<font color="#b7b7b7">
</div>
<div class="form-group">
<label for="title">Subject:</label>
<input type="text" name="title" id="title" value="{{$message->title}}" class="formcreateproducttitle" readonly="">
</div>
<div class="form-group">
<label for="text">Message:</label>
<textarea name="text" class="formcreateproductdesc" style="resize:none" rows="8" cols="80" readonly="">{{$message->text}}</textarea>
</div>
<div class="form-group">
<center>
@if(Auth::user()->id == $message->To->id)
<a href="{{route('sendmessage',['username'=>$message->From->username])}}" class="btn btn-primary">Reply</a>
@elseif(Auth::user()->id == $message->From->id)
<a href="{{route('sendmessage',['username'=>$message->To->username])}}" class="btn btn-primary">Send another message to {{$message->To->username}}</a>
@endif
</center>
</div></font>
我希望在默认代码之前添加代码:
<table class="table table-hover">
<thead>
<th>Title</th>
<th>text</th>
</thead>
<tbody>
@foreach($message as $messages)
<tr>
<td><?php $user = DB::table('messages')->where(['from'=> $message->from])->first(); echo $user->title; ?></td>
<td> </td>
@endforeach
</tr>
</tbody>
</table>
控制器:
public function ViewMessage($uniqueid){
$message = Message::where('uniqueid',$uniqueid)->first();
if ($message == null) {
return redirect()->route('messages');
}
if ($message->viewed == false && Auth::user()->id == $message->to) {
$message->viewed = true;
$message->save();
}
return view('message.view')->with([
'message'=>$message
]);
}
但是现在我只看到每行中来自DB的用户之间的第一条消息,我认为因为->first();
正确吗?
我如何显示2个用户之间的所有消息,而不仅仅是第一个? 或者从发件人那里我只能在上面的代码中做得更好。
非常感谢
答案 0 :(得分:1)
使用查询构建器:
public static function getAChatMessages($receiverUserId, $senderUserId)
{
$firstMessages = DB::tabel("message")->where([['from',$receiverUserId],
['to',senderUserId]])->orderBy('dateTime','DESC')->get();
$allMessages = DB::tabel("message")->where([['to',$receiverUserId],
['from',senderUserId]])->union(firstMessages)->orderBy('dateTime','DESC')->get();
return $allMessages();
}
答案 1 :(得分:0)
'first()'函数只返回第一条消息,你需要用'get()'来改变它,并对所有消息进行迭代。
public function ViewMessage($uniqueid){
//it will return a collection of messages
$message = Message::where('uniqueid',$uniqueid)->get();
if ($message == null) {
return redirect()->route('messages');
}
//use loop to check on every message
foreach ($message as $m) {
if ($m->viewed == false && Auth::user()->id == $m->to) {
$m->viewed = true;
$m->save();
}
}
return view('message.view')->with([
'message'=>$message
]);
}