Laravel E-Commerce Application Development – Settings Section Part 1

Laravel E-Commerce Application Development – Settings Section Part 1

Laravel E-Commerce Application Development ( 19 Lessons )

In this course, you’ll learn how to create an E-Commerce Website from scratch in Laravel. The process has never been easier I’ll take you from the very beginning stages of setting up Laravel till the last steps of adding products to the cart. If you’ve good understanding & experience in PHP & MySQL then this course is for you.

see full series
  1. Laravel E-Commerce Application Development – Introduction
  2. Laravel E-Commerce Application Development – Initial Project Setup
  3. Laravel E-Commerce Application Development – Assets Setup Using Laravel Mix
  4. Laravel E-Commerce Application Development – Admin Model and Migration
  5. Laravel E-Commerce Application Development – Backend Admin Authentication
  6. Laravel E-Commerce Application Development – Base Controller and Repository
  7. Laravel E-Commerce Application Development – Settings Section Part 1
  8. Laravel E-Commerce Application Development – Settings Section Part 2
  9. Laravel E-Commerce Application Development – Categories Section Part 1
  10. Laravel E-Commerce Application Development – Categories Section Part 2
  11. Laravel E-Commerce Application Development – Attributes Section Part 1
  12. Laravel E-Commerce Application Development – Attributes Section Part 2
  13. Laravel E-Commerce Application Development – Attributes Section Part 3
  14. Laravel E-Commerce Application Development – Brands Section
  15. Laravel E-Commerce Application Development – Products Section Part 1
  16. Laravel E-Commerce Application Development – Products Section Part 2
  17. Laravel E-Commerce Application Development – Products Section Part 3
  18. Laravel E-Commerce Application Development – Products Section Part 4
  19. Laravel E-Commerce Application Development – Frontend Login & Registration

This is the sixth part of the Laravel E-Commerce Application Development series, in this part will add the settings model, migration and seed.

I assume you should have the e-commerce application project on your machine or you can grab it from Laravel E-Commerce Application repository, we will start from where we left it in the last part.

Any web application’s backend needs to have some sort of a settings section from where you can change the various settings of your application. In our e-commerce application, we would like to have some settings such as site name, logos, shipping methods control, payment methods control and so on.

There are various packages available to add the settings functionality in your application, but I would like to implement it from scratch. I will share with you how I add the settings to any of my Laravel based application.

So let’s start some coding.

Settings Model & Migration

First thing first, we would like to save our settings in the database. So we need to add a model and migration for our settings table. Open your terminal and run the below command to generate the model and migration for settings.

php artisan make:model Models\\Setting -m

Above command will generate a Setting model in app/Models folder and a migration file in database/migrations folder.

Open the migration file for settings, and update with the below one.

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

class CreateSettingsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('settings', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('key')->unique();
            $table->text('value')->nullable();
            $table->timestamps();
        });
    }

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

We will be stroing the settings as key value pairs, so we simply added the key and value columns.

Now open your Setting model and replace with the below ones.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Setting extends Model
{
    /**
     * @var string
     */
    protected $table = 'settings';

    /**
     * @var array
     */
    protected $fillable = ['key', 'value'];
}

Settings Seed

Next, we will add a database seed for our settings table. Run below command in the terminal.

php artisan make:seed SettingsTableSeeder

Above command will generate a database seed in database/seeds folder. Open the SettingsTableSeeder class and add the $settings property in the class. This $settings will have an array which will contain the key/value pairs of the settings we want to manage.

use App\Models\Setting;
use Illuminate\Database\Seeder;

class SettingsTableSeeder extends Seeder
{
    /**
     * @var array
     */
    protected $settings = [
        [
            'key'                       =>  'site_name',
            'value'                     =>  'E-Commerce Application',
        ],
        [
            'key'                       =>  'site_title',
            'value'                     =>  'E-Commerce',
        ],
        [
            'key'                       =>  'default_email_address',
            'value'                     =>  '[email protected]',
        ],
        [
            'key'                       =>  'currency_code',
            'value'                     =>  'GBP',
        ],
        [
            'key'                       =>  'currency_symbol',
            'value'                     =>  '£',
        ],
        [
            'key'                       =>  'site_logo',
            'value'                     =>  '',
        ],
        [
            'key'                       =>  'site_favicon',
            'value'                     =>  '',
        ],
        [
            'key'                       =>  'footer_copyright_text',
            'value'                     =>  '',
        ],
        [
            'key'                       =>  'seo_meta_title',
            'value'                     =>  '',
        ],
        [
            'key'                       =>  'seo_meta_description',
            'value'                     =>  '',
        ],
        [
            'key'                       =>  'social_facebook',
            'value'                     =>  '',
        ],
        [
            'key'                       =>  'social_twitter',
            'value'                     =>  '',
        ],
        [
            'key'                       =>  'social_instagram',
            'value'                     =>  '',
        ],
        [
            'key'                       =>  'social_linkedin',
            'value'                     =>  '',
        ],
        [
            'key'                       =>  'google_analytics',
            'value'                     =>  '',
        ],
        [
            'key'                       =>  'facebook_pixels',
            'value'                     =>  '',
        ],
        [
            'key'                       =>  'stripe_payment_method',
            'value'                     =>  '',
        ],
        [
            'key'                       =>  'stripe_key',
            'value'                     =>  '',
        ],
        [
            'key'                       =>  'stripe_secret_key',
            'value'                     =>  '',
        ],
        [
            'key'                       =>  'paypal_payment_method',
            'value'                     =>  '',
        ],
        [
            'key'                       =>  'paypal_client_id',
            'value'                     =>  '',
        ],
        [
            'key'                       =>  'paypal_secret_id',
            'value'                     =>  '',
        ],
    ];
    
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        foreach ($this->settings as $index => $setting)
        {
            $result = Setting::create($setting);
            if (!$result) {
                $this->command->info("Insert failed at record $index.");
                return;
            }
        }
        $this->command->info('Inserted '.count($this->settings). ' records');
    }
}

As you can see, we are adding the various settings for our application, we will be using them as we make the progress in this series. In the run() method, we are looping through the $settings property and creating a new record for each record.

Setting Model Set and Get Methods

Now, we will add two static methods in our app/Models/Setting model, the first will be get() and second will be set() method.

Open you Setting model and add the get() function like below.

/**
 * @param $key
 */
public static function get($key)
{
    $setting = new self();
    $entry = $setting->where('key', $key)->first();
    if (!$entry) {
        return;
    }
    return $entry->value;
}

In this method, we are simply querying the record by $key and returning the value for a given key.

Now we will add a set() method, which we will use to update the setting value.

/**
 * @param $key
 * @param null $value
 * @return bool
 */
public static function set($key, $value = null)
{
    $setting = new self();
    $entry = $setting->where('key', $key)->firstOrFail();
    $entry->value = $value;
    $entry->saveOrFail();
    Config::set('key', $value);
    if (Config::get($key) == $value) {
        return true;
    }
    return false;
}

In the above method, we are first checking if the given $key has any value in the database, then we are updating the value for the given setting. Next, we are setting the current key/value for setting to the Laravel Configuration, so we can load them using the Laravel config() helper function.

Don’t forget to add the Config class in your model using the use statement like use Config;

Registering Setting Model as Facade

Now using the service provider, we will bind our model to Laravel’s application container and register it as a facade so we can use the setting model like Setting::get() or Setting::set().

For this, we will run the below command to generate a service provider.

php artisan make:provider SettingServiceProvider

Register Service Provider

Don’t forget to register SettingServiceProvider in your config/app.php file.

Now open the SettingServiceProvider class and add the below code in the register method.

/**
 * Register services.
 *
 * @return void
 */
public function register()
{
    $this->app->bind('settings', function ($app) {
        return new Setting();
    });
    $loader = \Illuminate\Foundation\AliasLoader::getInstance();
    $loader->alias('Setting', Setting::class);
}

Above code firstly, bind the setting model and then using the AliasLoader, we register it as a facade.

Autoloading All Settings

In an ideal scenario, it will be very helpful if we load all our settings when our application boot up, so we can use the setting anywhere we want it.

To autoload all the settings update the boot() method of the SettingServiceProvider with below one.

/**
 * Bootstrap services.
 *
 * @return void
 */
public function boot()
{
    // only use the Settings package if the Settings table is present in the database
    if (!\App::runningInConsole() && count(Schema::getColumnListing('settings'))) {
        $settings = Setting::all();
        foreach ($settings as $key => $setting)
        {
            Config::set('settings.'.$setting->key, $setting->value);
        }
    }
}

In the above code example, firstly we are checking if the application is not running in the console and there is a table exist with the name settings. Then we are loading all settings from the Setting model and then setting all values using the Laravel Config class.

Conclusion

In this part, we have added the settings model, migration, seed and extra functionality for our settings section.

Code Repository

You can find the code base of this series on Laravel eCommerce Application repository.

In the next post, we will add the settings section in our admin area from where we will be able to update all our setting’s values.

If you have any question, please leave it in the comment box below.

12 comments on “Laravel E-Commerce Application Development – Settings Section Part 1

  1. Firstofall, Thank you for this great work.
    Why you choice to declare settings as a service?Why not like the other entiy in application

    Thank you

  2. Register Service Provider
    Don’t forget to register SettingServiceProvider in your config/app.php file.

    i can’t do this step, please help me

  3. $loader = \Illuminate\Foundation\AliasLoader::getInstance();
    $loader->alias(‘Setting’, Setting::class);
    can you please explain the use of these lines and also while registering the settingserviceprovider in provider array of config app.php file, why you didn’t add something like
    ‘View’ => Illuminate\Support\Facades\View::class,
    this line in alias array

    1. Hi,
      First thing we are using alias loader class to register the aliase of our facade which we usually do by adding into the alias array in app.php file.

      So you have asked that why we are not adding it in the aliase array is actually what we have done with aliase loader class from within our SettingServiceProvider class.

      Thanks

      1. thank you sir, I have one more question
        you are setting the settings using config set function in public static function set($key, $value = null) in setting facade, and in setting service provider file in boot function, again you are getting the settings from setting facade and setting it using the config Config::set(‘settings.’.$setting->key, $setting->value);
        and is there any way to check the output of any variable just like $settings = Setting::all(); i want to see the result of $setting.

        1. Using the facade set function we set the values to the database. While in the settings service provider when we use Config::set(), we are settings all setting values to Laravel’s session on application boot.

          Then we can get the value using the Laravel’s helper function like config('site_title');

          Hope to answered the question.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.