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