2016-08-07 8 views
1

2人のユーザー間でメッセージを表示する必要があります。私はテーブルconversationsを作成しました。con_iduser_idfriend_idフィールドを持っています。私は論理を書く方法を知らないので、メッセージはこれらの2人のユーザの間で書かれた人だけがuser_idfriend_idフィールドに表示されます。2人のユーザー間でメッセージを表示します。 Laravel

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(); 
} 
+0

ここでは 'Auth :: id'メソッドを使用して' where'節を使用する必要があります。ここを確認してください。 https://laravel.com/docs/4.2/security – Francisunoxx

+0

基本的な考え方ですが、バフをつけています。 'if($ sent_to == $ current_user_id){}'は、現在のユーザーID 。 – Script47

+0

@Francisunoxx私は知っています。しかし、私は正確にどのように知りません。 – feknuolis

答えて

1

は、認証ユーザが送信者(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は、認証と異なる場合、あなたが受信している::ユーザー() - > ID、そうでなければ、送信者です。 one-line-ifを使用して、メッセージのCSSスタイルを決定します。 注:Auth :: user() - > idを使用するには、実際にログインしていることを確認する必要があります。そうしないと、ユーザーがログインしていないと失敗します。この場合はミドルウェアを使用します。

関連する問題