Laravel Database Based Dynamic Mail Configuration Set Example

  • 23-07-2022
  • 624
  • Laravel 9
  • Haresh Chauhan

Laravel Database Based Dynamic Mail Configuration Set, How to set database dynamically based on client request in or Dynamic mail configuration with values from a database or Dynamic configuration set from the database, You or can say dynamic credential set for email form the database. If you want to fix your email credential from the database. But it is just not only for the email address. You can set all your configuration or setting which you want to set dynamic from the database. You want to set this post will help you.

All credentials will be dynamic and they will come from the database in the future you want to change it you can easy to change it from the seeder or you can create a crud operation in the admin panel for there you can easy to change your settings credential if you think to change your credential and want to change provider you can easily to change it from admin panel like API key and API secret key all that.

In this post i have take example of dynamic mail configuration setup, So having end of this post you will learn all you client-side credential dynamic very easily. Using seeder you can change your self there is no need to go inside coding for manually change you credential.

So let's start implementing mail dynamic configuration with the help of seeder.

Step 1: Create Project

First, We will create the laravel project so just copy the below-suggested command and paste it into your terminal and create a laravel new fresh project.

How To Add Google reCAPTCHA v3 In HTML Form Based PHP/Laravel Website

composer create-project laravel/laravel configuration

Step 2: Connect Database

After Successfully creating the laravel project we will config our database. First, I will go to my PHPMyAdmin and create a laravel name database.

Then we will put this laravel database name in the .env file you will find in your root file. If not found the .env file in your root just create and copy form .env.example file and config.

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

Step 3: Create Model & Migration

In this step, we will create a configuration model and migration for the configuration table. Just copy and paste below suggested command and create it.

php artisan make:model Configuration -m

Now, set up migration we will create three columns. column one we will take name this value name of the given value credential and in the second column slug from the name, we will create a slug this slug will help us to fetch data from the database. the column will be valued and in this column, we will store the value of the credential.

database/migrations/CreateConfigurationsTable.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateConfigurationsTable extends Migration
{
    /**
        * Run the migrations.
        *
        * @return void
        */
    public function up()
    {
        Schema::create('configurations', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('slug');
            $table->text('value');
            $table->timestamps();
        });
    }

    /**
        * Reverse the migrations.
        *
        * @return void
        */
    public function down()
    {
        Schema::dropIfExists('configurations');
    }
}

Now, we will set up the model of the configuration. set a fillable protected attribute as an array and in this array, we will add all properties.

app/Models/Configuration.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Configuration extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'slug',
        'value'
    ];
}

Now, we will migrate all that migration, Use the below-given command in your terminal this will create all tables from the migration in your database.

php artisan migrate

Step 4: Create Seeder

Now we will create a configuration seeder, Use the below command and create a seeder.

php artisan make:seeder AppConfigurationSeeder

After created will add email data inside the run method, You can see in the below example I have taken all that email credentials and added to the database configuration table.

database/seeder/AppConfigurationSeeder.php
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Configuration;
use Str;

class AppConfigurationSeeder extends Seeder
{
    /**
        * Run the database seeds.
        *
        * @return void
        */
    public function run()
    {
        $data = [
            [
                'name' => 'Mail Mailer',
                'slug' => Str::slug('Mail Mailer', '-'),
                'value' => 'smtp'
            ],
            [
                'name' => 'Mail Host',
                'slug' => Str::slug('Mail Host', '-'),
                'value' => 'smtp.mailtrap.io'
            ],
            [
                'name' => 'Mail Port',
                'slug' => Str::slug('Mail Port', '-'),
                'value' => '2525'
            ],
            [
                'name' => 'Mail Username',
                'slug' => Str::slug('Mail Username', '-'),
                'value' => '731a394e6f5e9d'
            ],
            [
                'name' => 'Mail Password',
                'slug' => Str::slug('Mail Password', '-'),
                'value' => 'fa2bf243527a27'
            ],
            [
                'name' => 'Mail Encryption',
                'slug' => Str::slug('Mail Encryption', '-'),
                'value' => 'tls'
            ],
        ];

        foreach ($data as $key => $value){
            Configuration::create($value);
        }
    }
}

Then, set up all that email credential details like port, host, username, and password all that we will run this seeder. Use the below-given command. This command will run your seeder and create all rows inside the table.

php artisan db:seed --class=AppConfigurationSeeder

Step 5: Create Provider

Use the below command and create a service provider. Use the below-suggested command. This command will create a service provider in your app/Providers path.

app/Providers/AppConfigurationProvider.php
php artisan make:provider AppConfigurationProvider

Well, Now we will be done also in this step we will fetch all data from the configuration table using the pluck method.

Using Config::set() we will set all that email configuration in our mail.php file. You can see the below example just follow it.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Models\Configuration;
use Config;

class AppConfigurationProvider extends ServiceProvider
{
    /**
    * Register services.
    *
    * @return void
    */

    public function register()
    {
        //
    }

    /**
    * Bootstrap services.
    *
    * @return void
    */

    public function boot()
    {
        $configuration = Configuration::pluck('value','slug')->toArray();
        
        Config::set('mail.default',$configuration['mail-mailer']);
        Config::set('mail.mailers.smtp.port',$configuration['mail-port']);
        Config::set('mail.mailers.smtp.host',$configuration['mail-host']);
        Config::set('mail.mailers.smtp.encryption',$configuration['mail-encryption']);
        Config::set('mail.mailers.smtp.username',$configuration['mail-username']);
        Config::set('mail.mailers.smtp.password',$configuration['mail-password']);
    }
}

After setting all, we will register that created service provider to our app.php file. I will go to the app.php file inside the config folder and will register that create service provider inside the provider attribute as below given example.

config/app.php
'providers' => [
    App\Providers\AppConfigurationProvider::class,
],

Step 6: Routes & Mail-Send

Now, all the email credential in my application is dynamic. I want to test by sending an email. So I set up my simple mail send example in web.php inside the routes folder.

routes/web.php
<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {

    $data = array('name'=>"Webappfix");
    
    \Mail::send('mail',['data' => $data], function($message) {
        $message->to('abc@gmail.com', 'Webappfix')
        ->subject('Laravel Dynamic mail config send mail')
        ->from('xyz@gmail.com','abc');
    });

    dd("Basic Email Sent. Check your inbox.");

    return view('welcome');
});

Step 7: Start Development Server

Using blow given command we will run our application development server.

php artisan serve
OUTPUT EMAIL SEND:
image

CONCLUSION:

Laravel provides client-side dynamic configuration. If you go to the config folder you will see inside there are a file services.php file. This file is provided by Laravel only for dynamic configuration purposes. You can set all that config in the services file and you can fetch from this file very easily.


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :