Joy
Joy

Reputation: 298

how to use third party service credentials from database in laravel 5.4?

Suppose I am using multiple Email services (e.g Mailgun, Mailchimp etc), now I want to store the credentials of each email service in the database instead of config/service.php. So that I can call/use different email services for sending email in a different situation.

Upvotes: 0

Views: 104

Answers (1)

Vipertecpro
Vipertecpro

Reputation: 3274

This may not be the solution but this will help for sure, Okay first create database like that

CREATE TABLE `mail_settings` (
  `id` int(10) UNSIGNED NOT NULL,
  `mail_driver` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `mail_host` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `mail_port` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `mail_username` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `mail_password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `mail_encryption` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `deleted_at` timestamp NULL DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Same fields as in .env

MAIL_DRIVER=
MAIL_HOST=
MAIL_PORT=
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=

Then set MailServiceProvider,

public function register()
{  
    if (\Schema::hasTable('mail_settings')) {
        //TRY TO MAKE THIS QUERY SOMEHOW DYNAMIC
        $mail = DB::table('mail_settings')->where('mail_driver','smtp.mailtrap.io')->first();
        if ($mail) //checking if table is not empty
        {
            $config = array(
                'driver'     => $mail->mail_driver,
                'host'       => $mail->mail_host,
                'port'       => $mail->mail_port,
                'from'       => array('address' => '[email protected]', 'name' => 'someone'),
                'encryption' => $mail->mail_encryption,
                'username'   => $mail->mail_username,
                'password'   => $mail->mail_password,
            );
            Config::set('mail', $config);
        }
    }
}

I hope this helps.

Upvotes: 2

Related Questions