08
MarLaravel 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:
error
messages on the website.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
If you want to create an email digest, make sure you have the following first:
array
variable in its constructor, this array variable will contain all the records of data
passed 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.
config\laravel-digest.php
by setting amount.enabled => true
and frequency.enabled => false
<?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');
}
}
view
to render the names of the users resources\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>
observer
for 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);
}
}
If you want to dig more about this package, you can visit its complete documentation and source code on Github.
Published at : 08-03-2022
I am a highly results-driven professional with 12+ years of collective experience in the grounds of web application development especially in laravel, native android application development in java, and desktop application development in the dot net framework. Now managing a team of expert developers at Codebrisk.
Launch project