Message.php
3.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use mysql_xdevapi\Collection;
class Message extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'to_user_id',
'title',
'text',
'file',
'flag_new',
'ad_employer_id',
'job_title_id',
'chat_id_from',
'chat_id_to',
'reply_message_id',
'original_file_name',
];
/*
* Связь таблицы Message с таблицей User (Отправитель)
*/
public function user_from() {
return $this->belongsTo(User::class, 'user_id');
}
/*
* Связь таблицы Message с таблицей User (Получатель)
*/
public function user_to() {
return $this->belongsTo(User::class, 'to_user_id');
}
// Связь модели Сообщения (Message) с моделью Вакансии (Ad_employer)
public function vacancies() {
return $this->belongsTo(Ad_employer::class, 'ad_employer_id', 'id');
}
public static function add_message(
?Request $request,
int $user_id,
int $to_user_id,
array $message_params,
string $file_store_path = '/',
bool $is_admin_chat = false
) {
dd($request->all());
$message_params['user_id'] = $user_id;
$message_params['to_user_id'] = $to_user_id;
if ($request && $request->has('file')) {
$file = $request->file('file');
$message_params['file'] = $file->store($file_store_path, 'public');
$message_params['original_file_name'] = $file->getClientOriginalName();
}
$chat_form = Chat::firstOrCreate([
'user_id' => $is_admin_chat ? 0 : $user_id,
'to_user_id' => $to_user_id,
'is_removed' => 0,
'is_admin_chat' => $is_admin_chat ? 1 : 0,
]);
$message_params[$is_admin_chat ? 'chat_id_to' : 'chat_id_from'] = $chat_form->id;
if (!$is_admin_chat) {
$chat_to = Chat::firstOrCreate([
'user_id' => $to_user_id,
'to_user_id' => $user_id,
'is_removed' => 0
]);
$message_params['chat_id_to'] = $chat_to->id;
}
$new_message = Message::create($message_params);
if (!empty($new_message->id)) {
$chat_form->update(['last_message_date' => date("Y-m-d H:i:s"), 'last_message_id' => $new_message->id]);
if (!$is_admin_chat) {
$chat_to->update(['last_message_date' => date("Y-m-d H:i:s"), 'last_message_id' => $new_message->id]);
}
}
return $new_message ?? false;
}
public function getReplyMessageAttribute()
{
$reply_message = false;
if ($this->attributes['reply_message_id']){
$reply_message = self::find($this->attributes['reply_message_id']);
}
return $reply_message;
}
}