Laravel 5: Console – Closure Based Method: Emailing

Artisan Console: Closure Based Method – Emailing


An example showing closure based method and sending email.

First we have to generate our mailable class.

This class defines and readies a few things:

  • you tell Laravel, where you place view file to be used for email body
  • you set from:email/name (unless you use default set in: app\conf\email, or .env file
  • set subject
  • inject type hinted dependencies and get, generate etc. any data you want to pass to view file (email body) – that includes styling, media etc.
  • plus anything else you may need

To generate file you may use Artisan command:

By default, your mailer class will be placed in directory:

You can place it inside of sub-directory directly from Artisan, e.g.:

Created class is a pretty boilerplate.

After a few updates, I got this:

 


Create view file, that will be used for email body

This can be done by hand.

Such file should reside somewhere in folder:

I put mine deeper in sub-directory:

And this is my simple, demo file:

 


Create Artisan command.

Since I am vivisecting now Laravel’s scheduling and connected to it Artisan command system, I need command to be defined and registered with Artisan console.

I chose Closure method.

This method is located in this file:

And here it is:

 

A few words of explanation.

Asterisk after ‘userdata’ denotes, that ‘userdata’ is an array. More here.

Userame comes from type-hinted dependency User.
$userdata fetches data coming from console via {userdata*}. It is an array.

 


Now, I have to schedule task to run.

Scheduling is done in this file:

… and this is how it looks:

This is our console command:

23 is arbitrary user id.
In real life, you’d probably do this dynamically.

Then there is a period – how often command fires.

 


Final result is this:

email

 

In a bit I will take a very close look at all available tools within mailer.