app/Http/Controllers/ConversationsController.php
/**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
Store a newly created resource in storage.
Store a newly created resource in storage .
public function store(Request $request)
    {
        $rules = [
            'receiver_id' => 'required'
        ];
        $validator = Validator::make($request->all(), $rules);
        $chats_with_receiver = Conversation::where(function($conv){
            $conv->where('sender_id', Auth::user()['id'])->where('receiver_id', request()['receiver_id']);
        })->orWhere(function($conv){
            $conv->where('receiver_id', Auth::user()['id'])->where('sender_id', request()['receiver_id']);
        })->get();
        if($validator->fails()){
            return response()->json($validator->errors(), 400);
        } else if (count($chats_with_receiver) > 0){
            return response()->json(["error" => "conversation exists"], 200);
        }
        $conversation = Conversation::create($request->all());
        $conversation->sender_id = Auth::user()['id'];
        $conversation->save();
        return response()->json($conversation, 201);
    }
public function store ( Request $ request ) { $ rules = [ 'receiver_id' => 'required' ] ; $ validator = Validator :: make ( $ request -> all ( ) , $ rules ) ; $ chats_with_receiver = Conversation :: where ( function ( $ conv ) { $ conv -> where ( 'sender_id' , Auth :: user ( ) [ 'id' ] ) -> where ( 'receiver_id' , request ( ) [ 'receiver_id' ] ) ; } ) -> orWhere ( function ( $ conv ) { $ conv -> where ( 'receiver_id' , Auth :: user ( ) [ 'id' ] ) -> where ( 'sender_id' , request ( ) [ 'receiver_id' ] ) ; } ) -> get ( ) ; if ( $ validator -> fails ( ) ) { return response ( ) -> json ( $ validator -> errors ( ) , 400 ) ; } else if ( count ( $ chats_with_receiver ) > 0 ) { return response ( ) -> json ( [ " error " => " conversation exists " ] , 200 ) ; } $ conversation = Conversation :: create ( $ request -> all ( ) ) ; $ conversation -> sender_id = Auth :: user ( ) [ 'id' ] ; $ conversation -> save ( ) ; return response ( ) -> json ( $ conversation , 201 ) ; }
Store a newly created resource in storage.
Store a newly created resource in storage .
// Return existing conversations, if any exist