- Laravel Version: 8.78.1
- PHP Version: 8.0.10
I’ve created a custom command to run on a schedule and email a notification.
My Command class handle method:
public function handle()
{
$sql = "SELECT * FROM Licences WHERE (Expired = 1)";
$list = DB::select($sql);
return (new NotifyExpiredLicences($list))->toMail('[email protected]');
}
My notification method:
public function toMail($notifiable)
{
return (new MailMessage)
->subject('Clients with Expired Licences')
->markdown('vendor/notifications/expiredlicences',
['clients' => $this->list, 'toname' => 'Me']);
}
Whenever I test this by running it manually with php artisan email:expired-licences
I get the following error Object of class IlluminateNotificationsMessagesMailMessage could not be converted to int
from my command class in the handle method.
However, the preview of my email works fine & displays as expected:
Route::get('/notification', function () {
return (new SendExpiredLicences())->handle();
});
If I remove the return
statement from my handle()
method, then although I get no errors, neither in my console or in storagelogs, also the preview stops working.
At this point I’m sure I’ve missed something important from the way this is supposed to be done, but after going through the Laravel docs and looking at online tutorials/examples, I’ve no idea what.
2
Answers
I've got everything working - though not entirely sure it's the "Laravel way". If anyone's got suggestions for improving it - add a comment or new answer and I'll try it out.
ConsoleKernel.php:
AppConsoleCommandsSendExpiredLicences.php:
AppNotificationsNotifyExpiredLicences.php:
AppMailExpiredLicences.php:
resourcesviewsemailsexpiredlicences.blade.php:
For previewing with the browser routesweb.php:
Ok just to save more commenting, here’s what I’d recommend doing. This is all based on the Laravel docs, but there are multiple ways of doing it, including what you’ve used above. I don’t really think of them as "right and wrong," more "common and uncommon."
ConsoleKernel.php: I’d keep this mostly as-is, but pass the email to the command from a config file, rather than having it fixed in the command.
config/myapp.php:
AppConsoleCommandsSendExpiredLicences.php: update the command to accept the email address as an argument, use on-demand notifications, and get rid of
preview()
method. Neither the command or the notification need to know about the client list, so don’t build it yet.AppNotificationsNotifyExpiredLicences.php: the
toMail()
method should pass the notifiable object (i.e. the user getting notified) along, because the mailable will be responsible for adding the To address before the thing is sent.AppMailExpiredLicences.php: since the mail message actually needs the list of clients, this is where we build it. We get the recipient here, either from the user’s email or the anonymous object.
For previewing with the browser routesweb.php: