Mail Flashcards
How can you create a database table to hold your notifications using Artisan?
php artisan make:notifications-table
php artisan migrate
If a notification supports being stored in a database table, you should define a toDatabase or toArray method on the notification class. What would this method do?
It will receive a $notifiable entity and should return a plain PHP array. The returned array will be encoded as JSON and stored in the data column of your notifications table.
What is the difference between using toDatabase or toArray?
The toArray method is also used by the broadcast channel to determine which data to broadcast to your JavaScript powered frontend. If you would like to have two different array representations for the database and broadcast channels, you should define a toDatabase method instead of a toArray method.
How can you mark a users notifications as read?
assuming that the user was already specified and set as $user:
$user->unreadNotifications()->markAsRead();
Where can you find when a notification was read by a user on the notifications database record?
In the read_at column
All broadcast notifications are queued for broadcasting. If you would like to configure the queue connection or queue name that is used to queue the broadcast operation, how can you do that?
You may use the onConnection and onQueue methods of the BroadcastMessage:
return (new BroadcastMessage($data)) ->onConnection('sqs') ->onQueue('broadcasts');
How can you customize the type of your notification?
public function broadcastType(): string { return 'broadcast.message'; }
Notifications will broadcast on a private channel formatted using a {notifiable}.{id} convention. So, if you are sending a notification to an App\Models\User instance with an ID of 1, what will the notification’s private channel be called?
App.Models.User.1
What do you need to call a method that customizes which channel an entity’s broadcast notifications are broadcast on?
public function receivesBroadcastNotificationsOn(): string { return 'example.'.$this->id; }
In this example, the channel would be called example.x with x being the ID of the broadcast notification.
What component does Laravel use for SMS notifications?
Vonage
What is the name of the environmental variable that defines the phone number that your SMS messages should be sent from by default?
VONAGE_SMS_FROM
How can you send notifications from a phone number that is different than the default one set by the environmental variable?
->from('insert number here');
How can you keep track of costs per user, team or client?
By adding a client reference to the notification. Vonage will allow you to generate reports using this client reference so that you can better understand a particular customer’s SMS usage. The client reference can be any string up to 40 characters:
public function toVonage(object $notifiable): VonageMessage { return (new VonageMessage) ->clientReference((string) $notifiable->id) ->content('Your SMS message content'); }
Which method do you need to use to route Vonage notifications to the proper phone number?
public function routeNotificationForVonage(Notification $notification): string { return $this->phone_number; }
What do you need to install before being able to send Slack notifications? Give the installation command using composer!
composer require laravel/slack-notification-channel
Additionally, you must create a Slack App for your Slack workspace.
How should you name the method that generates Slack notifications and what should it return?
public function toSlack(object $notifiable): SlackMessage
Define a toSlack method that returns a text, headerBlock, contextBlock, sectionBlock and actionsBlock that lets the user confirm or deny something through slack!
public function toSlack(object $notifiable): SlackMessage { return (new SlackMessage) ->text('One of your invoices has been paid!') ->headerBlock('Invoice Paid') ->contextBlock(function (ContextBlock $block) { $block->text('Customer #1234'); }) ->sectionBlock(function (SectionBlock $block) { $block->text('An invoice has been paid.'); }) ->actionsBlock(function (ActionsBlock $block) { $block->button('Acknowledge Invoice') ->primary() ->confirm( 'Acknowledge the payment and send a thank you email?', function (ConfirmObject $dialog) { $dialog->confirm('Yes'); $dialog->deny('No'); } ); }); }
How can you display a preview of the payload and notification you are trying to build for Slack?
->dd();
using dump and die on a SlackMessage instance will generate and dump a URL to Slack’s Block Kit Builder, which displays a preview of the payload and notification in your browser. You may pass true to the dd method to dump the raw payload.
Make Slack route its notifications to the “#support-channel” Slack channel!
public function routeNotificationForSlack(Notification $notification): mixed { return '#support-channel'; }
When defining a custom notification channel for Laravel, which methods do you need to include, which arguments does that method need and what should it do?
Within the class for the custom channel, you need to create a send function that receives a $notifiable object and and a Notification $notification. It should return void and within the send method you may call methods on the notification to retrieve a message object understood by your channel and then send the notification to the $notifiable instance however you wish. To just give an example:
public function send(object $notifiable, Notification $notification): void { $message = $notification->toVoice($notifiable); // Send notification to the $notifiable instance... }
Where can you configure your applications mail configuration file?
config/mail.php
Each mailer configured within this file may have its own unique configuration and even its own unique “transport”, allowing your application to use different email services to send certain email messages.
Generate a mailable class using Artisan!
php artisan make:mail ExampleMailing
What do the envelope and content methods of a mailable class do?
The envelope method returns an Illuminate\Mail\Mailable\Envelope object that defines the subject and, sometimes, the recipients of the message. The content method returns an Illuminate\Mail\Mailables\Content object that defines the Blade template that will be used to generate the message content.
How can you set the sender and subject of the email in the envelope?
return new Envelope( from: new Address('example@example.com', 'Max Mustermann'), subject: 'Your example has been exampled', );
Within the config/mail.php configuration file, how can you set up a global email address to be used for all sent mails?
'from' => [ 'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'), 'name' => env('MAIL_FROM_NAME', 'Example'), ],
MAIL_FROM_ADDRESS and MAIL_FROM_NAME are environmental variables that should be set in the config/mail.php file if you wish to set them.
How can you set up which Blade template to use for the email’s content?
public function content(): Content { return new Content( view: 'mail.orders.shipped', ); }
In this case, the shipped Blade template would be used as the main content of the email.
Define the content for an email. so that there is a full Blade version, but also a plain text version of the mail available!
return new Content( html: 'mail.orders.shipped', text: 'mail.orders.shipped-text' );
html and view are interchangeable when defining your content, so this does the same thing as this would do:
return new Content( view: 'mail.orders.shipped', text: 'mail.orders.shipped-text' );
How can you add an attachment to your mails inside of the related mailable’s class?
public function attachments(): array { return [ Attachment::fromPath('/path/to/file'), ]; }
If you have stored a file on one of your filesystem disks, how can you attach it to the email?
Using the fromStorage attachment method:
return [ Attachment::fromStorage('/path/to/file'), ];
How can you embed inline images into your emails?
By using the embed method of the $message variable within your email template. For example:
<body> Here is an image: <img src="{{ $message->embed($pathToImage) }}"> </body>
The $message variable is automatically made available to all your email templates thanks to Laravel, so you don’t need to pass it manually.
How can you attach objects onto emails?
First you need to implement the Illuminate\Contracts\Mail\Attachable interface on the object that will be attachable to messages. This interface dictates that your class defines a toMailAttachment method that returns an Illuminate\Mail\Attachment instance.
Generate a mailable with a corresponding Markdown template!
php artisan make:mail OrderShipped –markdown=mail.orders.shipped
You can use the markdown when configuring the mailable Content definition within its content method instead of the view parameter
How can you export all of the Markdown mail components to your own application for customization?
php artisan vendor:publish –tag=laravel-mail
Which method of the Mail facade is used to send an email?
Calling the to method on the Mail facade accepts an email address, a user instance, or a collection of users. If you pass an object or collection of objects, the mailer will automatically use their email and name properties when determining the email’s recipients, so make sure these attributes are available on your objects. Once you have cpecified your recipients, you may pass an instance of your mailable class to the send method.
How can you set the cc and bcc recipients?
By chaining their respective methods together:
Mail::to($request->user()) ->cc($moreUsers) ->bcc($evenMoreUsers) ->send(new OrderShipped($order));
Occasionally, you may need to send a mailable to a list of recipients by iterating over an array of recipients / email addresses. However, there is a problem you will run into when trying to do that. Explain the issue!
Since the to method appends email addresses to the mailable’s list of recipients, each iteration through the loop will send another email to every previous recipient. Therefore, you should always re-create the mailable instance for each recipient.
How can you add mails onto the queue?
The queue method on the Mail facade will automatically take care of queueing your mails after specifying the message’s recipients.
If you wish to delay the delivery of a queued email, which method should you use and which arguments does it accept?
The later method accepts a DateTime instance as its first argument and the mailable object as the second one. For example:
Mail::to($request->user()) ->cc($moreUsers) ->bcc($evenMoreUsers) ->later(now()->addMinutes(10), new OrderShipped($order));
If you have a mailable class that you always want to be queued, how can you assure that everything in that class gets queued by default?
You may implement the ShouldQueue contract on the class. Now, even if you call the send method when mailing, the mailable will still be queued since it implements the contract
When queued mailables are dispatched within database transactions, they may be processed by the queue before the database transaction has been committed. When this happens, any updates you have made to models or database records during the database transaction may not yet be reflected in the database. In addition, any models or database records created within the transaction may not exist in the database. If your mailable depends on these models, unexpected errors can occur when the job that sends the queued mailable is processed. What can you do about this?
If your queue connection’s after_commit configuration option is set to false, you may still indicate that a particular queued mailable should be dispatched after all open database transactions have been committed by calling the afterCommit method when sending the mail message. Alternatively, you may call the afterCommit method from your mailable’s constructor.