السلام عليكم ..
السؤال كيف يتم تحديد اليوزر المرسلة الية وتضمين الرساله بأسم المرسل .
يجب إنشاء علاقات بين الجداول من نوع one to many ثم استخدام تقنيات الزمن الحقيقي لتحقيق المطلوب.
قم بتقسيم المهمة إلى 6مراحل فرعية:
لماذا نحتاج علاقة من نوع 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);
التعليقات