Skip to content

Instantly share code, notes, and snippets.

@bewithdhanu
Created November 29, 2022 10:08
Show Gist options
  • Save bewithdhanu/37c72dd72c032af425bc9abf676697b5 to your computer and use it in GitHub Desktop.
Save bewithdhanu/37c72dd72c032af425bc9abf676697b5 to your computer and use it in GitHub Desktop.
Common code for chat
// routes/api.php
Route::post('get/user/chat', [UserController::class, 'getChatOfUser']);
Route::post('chat/send/message', [UserController::class, 'sendMessage']);
Route::get('chat/list', [UserController::class, 'getChatUsers']);
// Migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateChatTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('chat', function (Blueprint $table) {
$table->id();
$table->bigInteger('reciever_id')->nullable();
$table->bigInteger('sender_id')->nullable();
$table->text('message')->nullable();
$table->string('is_read', 10)->nullable()->default('0');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('chat');
}
}
// Chat Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Chat extends Model
{
use HasFactory;
protected $table = 'chat';
protected $fillable = ['reciever_id', 'sender_id', 'message'];
protected $casts = [
'created_at' => 'datetime:Y-m-d H:i:s', 'updated_at' => 'datetime:Y-m-d H:i:s'
];
public function recieverDetail()
{
return $this->hasone(User::class, 'id', 'reciever_id');
}
public function senderDetail()
{
return $this->hasone(User::class, 'id', 'sender_id');
}
}
// API Implementation
public function getChatUsers()
{
$response = [];
$reciever_id = \Auth::id();
$data = Chat::with('senderDetail:id,name,image')->where(['reciever_id' => $reciever_id])->select('sender_id', 'message', 'created_at')->orderByDesc('id')->get();
if ($data->isNotEmpty()) {
$data = $data->unique('sender_id');
$data = $data->values();
}
$response['message'] = "Get Chat list";
$response['data'] = $data;
$response['success'] = TRUE;
$response['status'] = STATUS_OK;
return response()->json($response, $response['status']);
}
public function getChatOfUser(Request $request)
{
$response = [];
$response['success'] = FALSE;
$response['status'] = STATUS_BAD_REQUEST;
$rules = [
'reciever_id' => 'required|numeric|exists:users,id',
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
$errorResponse = validation_error_response($validator->errors()->toArray());
return response()->json($errorResponse, $response['status']);
}
$senderId = \Auth::id();
if ($senderId == $request->reciever_id) {
$validator->errors()->add('reciever_id', 'Sender and Reciever id could not be same');
$errorResponse = validation_error_response($validator->errors()->toArray());
return response()->json($errorResponse, $response['status']);
}
$sql = "SELECT * FROM chat where (reciever_id = " . $request->reciever_id . " and sender_id = " . $senderId . ") or (reciever_id = " . $senderId . " and sender_id = " . $request->reciever_id . ")";
$data = DB::select($sql);
if (!empty($data)) {
$map = array_map(function ($arr) {
return $arr->id;
}, $data);
$data = Chat::with('senderDetail:id,name,image', 'recieverDetail:id,name,image')->whereIn('id', $map)->get();
}
$response['message'] = "Get Chat successfully";
$response['data'] = $data;
$response['success'] = TRUE;
$response['status'] = STATUS_OK;
return response()->json($response, $response['status']);
}
public function sendMessage(Request $request)
{
$response = [];
$response['success'] = FALSE;
$response['status'] = STATUS_BAD_REQUEST;
$rules = [
'reciever_id' => 'required|numeric|exists:users,id',
'message' => 'required|string',
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
$errorResponse = validation_error_response($validator->errors()->toArray());
return response()->json($errorResponse, $response['status']);
}
$senderId = \Auth::id();
if ($senderId == $request->reciever_id) {
$validator->errors()->add('reciever_id', 'Sender and Reciever id could not be same');
$errorResponse = validation_error_response($validator->errors()->toArray());
return response()->json($errorResponse, $response['status']);
}
$input = $request->all();
$input['sender_id'] = $senderId;
Chat::create($input);
$title = "New Message";
$message = \Auth::user()->name . " send you a new message";
$type = "chat_message";
$user = User::find($request->reciever_id);
if ($user->device_token != "") {
$this->sendPushNotification($user->device_token, $title, $message, $type);
}
$data = Chat::with('senderDetail:id,name,image', 'recieverDetail:id,name,image')->where(['reciever_id' => $request->reciever_id, 'sender_id' => $senderId])->orWhere(['reciever_id' => $senderId, 'sender_id' => $request->reciever_id])->get();
$response['message'] = "message send successfully";
$response['data'] = $data;
$response['success'] = TRUE;
$response['status'] = STATUS_OK;
return response()->json($response, $response['status']);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment