Message.php 2.16 KB
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class Message extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'to_user_id',
        'title',
        'text',
        'file',
        'flag_new',
        'ad_employer_id',
        'job_title_id'
    ];


    /*
     * Связь таблицы 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 = '/'
    ) {
        $message_params['user_id'] = $user_id;
        $message_params['to_user_id'] = $to_user_id;
        if ($request->has('file')) {
            $message_params['file'] = $request->file('file')->store($file_store_path, 'public');
        }

        $new_message = Message::create($message_params);

        if (!empty($new_message->id)) {
            Chat::updateOrCreate(
                ['user_id' => $user_id, 'to_user_id' => $to_user_id],
                ['user_id' => $user_id, 'to_user_id' => $to_user_id, 'last_message_date' => date("Y-m-d H:i:s"), 'last_message_id' => $new_message->id]
            );

            Chat::updateOrCreate(
                ['user_id' => $to_user_id, 'to_user_id' => $user_id],
                ['user_id' => $to_user_id, 'to_user_id' => $user_id, 'last_message_date' => date("Y-m-d H:i:s"), 'last_message_id' => $new_message->id]
            );
        }

        return $new_message->id ?? 0;

    }

}