【问题标题】:Display messages between two users. Laravel显示两个用户之间的消息。拉拉维尔
【发布时间】:2016-08-08 00:40:36
【问题描述】:

我需要在两个用户之间显示消息。我创建了表conversations,它有con_iduser_idfriend_id 字段。我不知道如何编写逻辑,以便仅显示在user_idfriend_id 字段中的这两个用户之间写入的消息。

存储消息:

public function store(Request $request, $id)
{
    $conv = new Conversation();
    $conv->user_id = Auth::user()->id;
    $friend = User::where('id', $id)->first();
    $conv->friend_id = $friend->id;
    $conv->message = $request->input('message');
    $conv->save();
}

【问题讨论】:

  • 您需要在此处使用Auth::id 方法使用where 子句。在这里检查。 laravel.com/docs/4.2/security
  • 基本但这个想法只是这个但被加强了:if ($sent_to == $current_user_id) { }你会根据当前用户ID检查查询结果。
  • @Francisunoxx 我知道。但我不知道具体是怎样的。
  • @feknuolis 你能把你的控制器发布在这个逻辑发生的地方吗?
  • @Francisunoxx 我已经发布了store 方法

标签: php laravel


【解决方案1】:

获取消息,其中 Auth-user 是发送者 (user_id),接收者是friend_id,反之亦然。按时间排序(假设您有列 created_at)。

$sent_by_me = DB::table('conversations')
->select('message', 'user_id as sender_user_id', 'friend_id as receiver_user_id')
->where('user_id', Auth::user()->id)
->where('friend_id', $friend_id);

// messages sent to me by friend
$conversation = DB::table('conversations')
->select('message', 'user_id as sender_user_id' 'friend_id as receiver_user_id')
->where('user_id', $friend_id)
->where('friend_id', Auth::user()->id)
->union($sent_by_me)
->orderBy('created_at', 'asc')
->get(); 

return View::make('show.conversation')
     ->with('conversation', $conversation);

在刀片中,如果 sender_user_id 与 Auth::user()->id 不同,您就是接收者,否则您就是发送者。使用 one-line-if 来确定消息的 css 样式。 注意:在使用 Auth::user()->id 之前,你必须检查用户是否真的登录,否则如果用户没有登录,它会失败。在这种情况下使用中间件就可以了。

@forelse($conversation as $msg)
    <div id="message_{{ $msg->id }}" class="{{ $msg->sender_user_id === Auth::user()->id ? 'sent_message' : 'received_message' }}"> {{ $msg->message }} </div>
@empty
    No messages!
@endforelse

【讨论】:

    猜你喜欢
    • 2020-02-16
    • 2018-03-06
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2017-10-21
    • 2016-02-06
    • 2015-03-28
    • 2015-08-24
    相关资源
    最近更新 更多