Just got schooled in a Laravel feature I was unaware of:
— Chris Fidao (@fideloper) January 20, 2022
Tell Laravel to always send to a specific address! pic.twitter.com/sJJouTCzPn
There's an (as of yet) undocumented way in Laravel to prevent it from sending emails to any old address.
Why is this useful? Well, some of us aren't perfect 😅. Sometimes we accidentally send thousands of emails to real customers from our staging environment.
There are lots of ways to avoid this, but Laravel has a nice, easy method out of the box!
1# File app/Providers/AppServiceProvider.php 2 3use Illuminate\Support\Facades\Mail; 4use Illuminate\Support\ServiceProvider; 5 6class AppServiceProvider extends ServiceProvider 7{ 8 // Stuff omitted 9 10 public function boot()11 {12 f (! app()->environment('production')) {13 Mail::alwaysTo('foo@example.org');14 }15 }16}
What's Happening with alwaysTo?
The handy alwaysTo()
method will over-ride all addresses added in the to
, cc
, and bcc
within an email message.
This is done within the Illuminate\Mail\Mailer
class (see here). Note the code comment:
1// If a global "to" address has been set, we will set that address on the mail2// message. This is primarily useful during local development in which each3// message should be delivered into a single mail address for inspection.4if (isset($this->to['address'])) {5 $this->setGlobalToAndRemoveCcAndBcc($message);6}
So, in our code up above, we tell Laravel to only send emails to foo@example.org
if we are NOT in the production environment!
Filed in:
Teaching coding and servers at CloudCasts and Servers for Hackers. Co-founder of Chipper CI.