一、已读私信
新建 app/MessageCollection.php
namespace App;
use Illuminate\Database\Eloquent\Collection;
class MessageCollection extends Collection
{
public function markAsRead()
{
$this->each(function ($message){
if($message->to_user_id == user()->id){
$message->markAsRead();
}
});
}
}
新建 app/Message.php
public function markAsRead()
{
if(is_null($this->read_at)){
$data = [
'has_read' => 'T',
'read_at' => $this->freshTimestamp()
];
$this->forceFill($data)->save();
}
}
public function newCollection(array $models = [])
{
return new MessageCollection($models);
}
修改app/Repositories/MessageRepository.php
public function getMessageListByDialogId($dialogId)
{
$messages = Message::where('dialog_id', $dialogId)->latest()->get();
$messages->markAsRead();
return $messages;
}
二、未读私信
修改 app/Message.php
public function read()
{
return $this->has_read === 'T';
}
public function unread()
{
return $this->has_read === 'F';
}
public function isUnread()
{
if(user()->id === $this->from_user_id){
return false;
}
return $this->unread();
}
修改 app/Repositories/MessageRepository.php
public function getMessageList()
{
return Message::where('to_user_id',user()->id)
->orWhere('from_user_id',user()->id)
->with(['fromUser'=>function($query){
return $query->select(['id','name','avatar']);
},'toUser'=>function($query){
return $query->select(['id','name','avatar']);
}])
->latest()
->get()
->groupBy('dialog_id');
}
public function getMessageListByDialogId($dialogId)
{
$messages = Message::where('dialog_id', $dialogId)
->with(['fromUser'=>function($query){
return $query->select(['id','name','avatar']);
},'toUser'=>function($query){
return $query->select(['id','name','avatar']);
}])
->latest()
->get();
$messages->markAsRead();
return $messages;
}
修改 resources/assets/css/style.css
.a-avatar {
width: 75px;
display: block
}
.a-avatar2 {
width: 50px;
display: block
}
.avatar {
border-radius: 50%;
}
.unread {
background: #FAF1BD;
}
执行 gulp
gulp
修改 resources/views/inbox/index.blade.php
访问:http://127.0.0.1:8000/inbox 进行测试