Laravel Digest is a simple package to create and send digest emails every certain period or when the amount reaches a certain threshold. You can utilize this package in many ways like:
- Sending a digest email to the website administrator every new 100 registrations on the website.
- Sending a daily email with logged
errormessages on the website. - Sending users a monthly newsletter that contains all posts issued in the month.
Installation
You can install this package via composer by running this command in the terminal.
composer require hmones/laravel-digest
Configuration
Next, You’ve to run this command to publish the package configuration.
php artisan vendor:publish --tag=laravel-digest-config
Usage
If you want to create an email digest, make sure you have the following first:
- A mailable, configured with the sending addresses and email views and subject.
- The mailable should accept an
arrayvariable in its constructor, this array variable will contain all the records ofdatapassed to individual emails concatenated and sent automatically by the package to the mailable to compile the views for sending the digest.
Example:
Sending a digest email every time 10 new users register on the website with a summary of their names.
- Adjust the configuration variable in
config\laravel-digest.phpby settingamount.enabled => trueandfrequency.enabled => false - Create the following mailable:
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class UserCreatedMailable extends Mailable
{
use Queueable, SerializesModels;
public $data;
public function __construct(array $data)
{
$this->data = $data;
}
public function build(): Mailable
{
return $this->view('userCreated')->subject('10 new users are registered')->to('email@test.com');
}
}
- Create a
viewto render the names of the usersresources\userCreated.blade.php
<html>
<head><title>Sample Email</title></head>
<body>
<h1>The following users have just registered:</h1>
<ol>
@foreach($data as $record)
<li>{{$record['name']}}</li>
@endforeach
</ol>
</body>
</html>
- Create an
observerfor user creation and add a record to the digest every time a user is created:
<?php
namespace App\Observers;
use App\Mail\UserCreatedMailable;
use App\Models\User;
use Hmones\LaravelDigest\Facades\Digest;
class UserObserver
{
public function created(User $user)
{
$batchId = 'userCreated';
$mailable = UserCreatedMailable::class;
//Data can also be set to null if you don't want to attach any data to the email
$data = ['name' => $user->name];
//Frequency can take values such as daily, weekly, monthly, custom or an integer threshold 10, 20 ...etc
$frequency = 10;
Digest::add($batchId, $mailable, $data, $frequency);
}
}
- The package will take care of everything else and send emails once the number of registered users reached 10.
If you want to dig more about this package, you can visit its complete documentation and source code on Github.