ارسال message(حقلtext) من يوزر الى قاعدة البيانات وعرضها الى يوزر محدد laravel

السلام عليكم ..

السؤال كيف يتم تحديد اليوزر المرسلة الية وتضمين الرساله بأسم المرسل .


يجب إنشاء علاقات بين الجداول من نوع one to many ثم استخدام تقنيات الزمن الحقيقي لتحقيق المطلوب.

قم بتقسيم المهمة إلى 6مراحل فرعية:

  1. إنشاء جدول مستخدمين users يحوي الحقول التالية id - name - email
  2. إنشاء جدول للرسائل messages يحوي الحقول التالية: id - from - content - to
  3. بناء one to many relationship داخل ال models: User, Message
  4. إنشاء ال form الخاص بكتابة الرسالة وتحديد المرسل إليه
  5. إنشاء div لعرض محتوى الرسائل الواردة
  6. استخدام الزمن الحقيقي real-time لاستقبال الرسالة في نفس اللحظة التي تم الإرسال بها دون الحاجة للقيام بتحديث الصفحة

لماذا نحتاج علاقة من نوع one to many ؟

لأن المستخدم يستطيع إرسال الرسائل لأكثر من مستخدم، تستطيع الاطلاع على التوثيق الرسمي للارافل من هنا:

User

php artisan make:model User -m

// User Model
public function from(){
   return $this->hasMany(Message::class, 'from');
}
public function to(){
   return $this->hasMany(Message::class, 'to');
}

// users migration
Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password')->nullable();
    $table->rememberToken();
    $table->timestamps();
});

Message

php artisan make:model Message -m

// Message Model
public function user(){
   return $this->belongsTo(User::class, 'from');
}

// messages migration
Schema::create('messages ', function (Blueprint $table) {
      $table->bigIncrements('id');
      $table->string('content');
      $table->unsignedBigInteger('from');
      $table->foreign('from')->references('id')->on('users');
      $table->unsignedBigInteger('to');
      $table->foreign('to')->references('id')->on('users');
      $table->timestamps();
});

إرسال رسالة:

$to = 2; // المعرف الخاص بالشخص المرسل إليه 
$content= 'test message';
Message::create([
   'from' => auth()->user()->id,
   'content' => $content,
   'to' => $to,
]);

استقبال الرسالة:

$user = User::whereId(auth()->user()->id)->first();
$sent_messages = $user->to;
$names = [];
   foreach ($sent_messages as $message) {
      array_push($names, $message->from->name );
   }
dd($sent_messages);