Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Send emails to a single test email address for test environments in Laravel

When you’re working on a Laravel application, chances are you might be working with a lot of emails. For instance, every time, a new user is created, a welcome email and a confirmation email will be sent to the user.

There would be many such instances where emails will be fired. So, in your test environments, it doesn’t make sense to use different emails for various purposes.

What if we could just use a single email address and all the emails of the application would be sent to this email address? Well, today, I learned about how you would do this through this tweet.

The Mail::alwaysTo() method

There exists this alwaysTo() method in the Mail facade where you can specify a global to address to which all the emails of the application would be sent.

You can configure this in the boot method of your application’s AppServiceProvider like so.

use Illuminate\Support\Facades\Mail;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        if (!app()->isProduction()) {
            Mail::alwaysTo('[email protected]');
        }
    }
}

As you can tell, we can set this up for all the environments which are not production and we are good!

A universal recipient in the config

The other way that you can do this is by setting up a universal recipient by specifying the to option in the config/mail.php file like so.

'to' => [
    'address' => env('MAIL_TEST_EMAIL_ADDRESS', '[email protected]'),
    'name' => env('MAIL_TEST_NAME', 'Test User')
]

Now, all the email from the application will be sent to the email configured here.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?