Friday, August 25, 2017

Laravel Dynamic Mail Configuration With Values From Database

In Laravel we have config folder, where we have different files like app.php and mail.php etc where we can configure settings. For example for sending mail from Laravel application, we have to configure mail.php file with configs like mail driver, mail user name etc. This will work good for static information. But what if you want to override and use your own settings from database at run time.

For example you have different mail configurations for each users and you want to set it when user is logged in. I this blog I am going to show you how you can do this in Laravel 5.x

For example you have mail_settings table where you are saving mails settings for each user. Now when user is logged in we have to get settings of logged in user and set it in config. This is how you can do that.

We know that all laravel controller extends the Controller. So what you can do is in constructor of Controller.php file, you can set the mail settings.

Here is how you can do this.
public function __construct()
{
$this->middleware(function ($request, $next) {
if(Auth::user()){
//So user is logged in.
if(Auth::user()->parent_id != null){
//Get the mail settings.
$settings = MailSettings::where('user_id',Auth::user()->parent_id)->first();

if(isset($settings)){
//settting up mail config for the logged in user.
config( ['mail' => ['from' => ['address' => $settings->from_email, 'name' => $settings->from_name], 'host'=>$settings->mail_host, 'port'=>$settings->mail_port, 'username'=>$settings->mail_username,  'password'=>$settings->mail_password, 'encryption'=>$settings->mail_encryption, 'driver'=>$settings->mail_driver]]);
}
}
}
return $next($request);
});

}

So as you can see we are getting mail settings from table for logged in user and setting up it in config. This way you can override anything in the default config and set it run time.

No comments:

Post a Comment