Scheduled Messages Command Processing Issue in Laravel 11

I’m facing an issue with a Laravel console command designed to send scheduled messages, and I would appreciate any help or insights from the community.

Problem Description
I’ve implemented a command that retrieves scheduled messages from the database and dispatches a job to send each message. While the first message is processed correctly, subsequent messages seem to use the previous iteration’s values, leading to incorrect message dispatching.

Command Code
Here’s the code for the command:

<?php

namespace AppConsoleCommands;

use AppJobsSendScheduledMessageJob;
use AppModelsScheduledMessage;
use IlluminateConsoleCommand;


class SendScheduledMessages extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:send-scheduled-messages';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send scheduled messages';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $messages = ScheduledMessage::where('scheduled_at', '<=', now())
            ->where('is_sent', false)
            ->get();

        foreach ($messages as $message) {
            SendScheduledMessageJob::dispatch($message);
        }
    }
}

and here is my console route for scheduling the task

<?php

use AppModelsScheduledMessage;
use IlluminateFoundationInspiring;
use IlluminateSupportFacadesArtisan;
use IlluminateSupportFacadesLog;
use IlluminateSupportFacadesSchedule;
use IlluminateSupportFacadesStorage;

Artisan::command('inspire', function () {
    $this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote')->hourly();

Schedule::command('app:send-scheduled-messages')->everySecond()->description('Send scheduled messages');

and here is SendScheduledMessageJob

<?php

namespace AppJobs;

use AppModelsScheduledMessage;
use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateFoundationBusDispatchable;
use IlluminateQueueInteractsWithQueue;
use IlluminateQueueSerializesModels;
use IlluminateSupportFacadesDB;
use IlluminateSupportFacadesLog;
use IlluminateSupportFacadesStorage;

class SendScheduledMessageJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $message;

    /**
     * Create a new job instance.
     */
    public function __construct(ScheduledMessage $message)
    {
        $this->message = $message;
        Log::info($this->message->scheduled_at);
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {

        DB::transaction(function () {
            try {

                // Retrieve the messageable entity (the recipient)
                $messageable = $this->message->messageable;

                // Create a new message for the recipient with the content and sender ID
                $newMessage = $messageable->messages()->create([
                    'content' => $this->message->content,
                    'sender_id' => $this->message->sender_id,
                ]);

                // Check if the original message has attachments
                if ($this->message->attachments->isNotEmpty()) {
                    // Iterate through each attachment
                    foreach ($this->message->attachments as $attachment) {
                        // Generate a new path for the attachment, replacing the old message ID with the new one
                        $path = str_replace($this->message->id, $newMessage->id, $attachment->path);

                        // Determine the directory to remove after moving the file, up to "/attachments"
                        $path_to_remove = substr($attachment->path, 0, strpos($attachment->path, "/attachments"));

                        // Move the attachment to the new path
                        Storage::disk('public')->move($attachment->path, $path);

                        // Create a record for the attachment under the new message quietly (without raising events)
                        $newMessage->attachments()->createQuietly([
                            'path' => $path,
                            'name' => $attachment->name,
                        ]);

                        // Delete the old directory where the attachment was stored
                        Storage::disk('public')->deleteDirectory($path_to_remove);
                    }
                }

                // Mark the original message as sent
                $this->message->update(['is_sent' => true]);
            } catch (Exception $e) {
                // Log any exceptions
                Log::error('Failed to send message ID: ' . $this->message->id . ', Error: ' . $e->getMessage());
            }
        });
    }
}

these are scheduled messages which were added to database with following scheduled_at values

  • 2024-07-03 12:14:00
  • 2024-07-03 12:15:00
  • 2024-07-03 12:16:00
  • 2024-07-03 12:17:00

and these are logs which were generated

[2024-07-03 14:08:00] local.INFO: 2024-07-03 12:14:00
[2024-07-03 14:08:00] local.INFO: 2024-07-03 12:14:00
[2024-07-03 14:08:00] local.INFO: 2024-07-03 12:15:00
[2024-07-03 14:08:00] local.INFO: 2024-07-03 12:16:00

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật