Impementing global app settings for Laravel API? - laravel

I wish to implement a few global app settings, e.g. App name, first day of the week, and other feature flags. The end goal is to have these be fetched and edited by administrators through the API.
What might be the most convenient way of doing this? I've experimented with using a Settings model to store key-value pairs, but this doesn't make sense to me since the desired settings should be hard coded and won't change, and seeding the Settings table doesn't sound ideal. Thanks in advance!

You can access App name from Laravel provided config function.
$appName = config('app.name');
// This value is retrieved from .env file of APP_NAME=
If you have to store multiple values related with the week, you can create a new config file week.php
//config/week.php
return [
...
'first_day_of_the_week' => 0
];
In order to retrieve the first_day_of_the_week, you can use the same function config
$firstDayOfTheWeek = config('week.first_day_of_the_week')
Similar to other essential flags, you can create a new config file.
You can later cache your config variables using the following command.
php artisan config:cache
You can also create a Helper class inside any preferred location inside the laravel project. I keep my helper class inside App\Helpers.
<?php
namespace App\Helpers;
use Carbon\Carbon;
class DateHelpers
{
public const DATE_RANGE_SEPARATOR = ' to ';
public static function getTodayFormat($format = 'Y-m-d')
{
$today = Carbon::now();
$todayDate = Carbon::parse($today->format($format));
return $todayDate;
}
....
}
If you need to retrieve the method value in the Laravel project, you can access by
$getTodayDateFormat = App\Helpers\DateHelpers::getTodayFormat();
EDIT 1:
Based on the question description. You need to create one row in the settings table.
//create_settings_table.php Migration File
public function up()
{
// Create table for storing roles
Schema::create('settings', function (Blueprint $table) {
$table->increments('id');
$table->string('app_name')->default("My App Name");
$table->unsignedInteger('first_day_of_the_week')->default(1);
....
$table->timestamps();
});
}
You only need one row of the settings table to retrieve/update the default value.
//Retrieving the first day
$first_day_of_the_week = App\Setting::first()->first_day_of_the_week;
//Updating the first day
...
$first_day_of_the_week = request('first_day_of_the_week');
App\Setting::first()->update([
'first_day_of_the_week' => $first_day_of_the_week
]);

Related

Creating new table in octobercms

I must create new table in octobercms project and I followed documentation and added new migration file inside plugin update file I have create_currency_rates_table.php file and it has this codes
<?php namespace RainLab\User\Updates;
use Schema;
use October\Rain\Database\Updates\Migration;
class CreateCurrencyRateTable extends Migration
{
public function up()
{
Schema::create('currency_rates', function($table)
{
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('currency');
});
}
public function down()
{
Schema::drop('currency_rate');
}
}
when I used php artisan october:up it is not detecting new migration. How can I create new table?Can anyone help me?
You also need to update plugins\<author>\<plugin_name>\updates\version.yaml this file and add your file name there as well.
So, in your case, you added a file like create_currency_rates_table.php then you need to add details of your file in version.yaml
for ex:
1.0.1: First version of Demo
1.0.2:
- Description About what is this update about?
- create_currency_rates_table.php
now when you next time just login to backend this table will be created automatically.
if any doubt please comment.

Laravel Configuration update

I am working on Laravel. I have questions about update / add configuration dynamically. Let me tell you my question.
I am updating / add the global configuration of my project using the file_put_content in config file. I have another way, save configuration into the database and pull that configuration at the time of login to the system.
Which way is better to use and why?
one way is maintain seprate table for config data if your data is static means nothing have to change in that data. and then create provider to get your data and bind that data at run time
public function boot()
{
if (Schema::hasTable('roles')) {
$roles = Role::pluck('name', 'id')->all();
$data = collect($roles)->mapWithKeys(function ($item, $index) {
return [str_slug($item, '_') => $index];
})->all();
config(['configfilename.configkey' => $data]);
}
}
Like this you can get your config data at run time

Is there a way to extend user plgin in octoberCMS in production

I'm asking if there's any way to extend user plugin in OctoberCMS by adding more fields when the site is already in production. I know how to do this in development but I don't know how to do it i production. Help
just create new plugin in development which is going to extend your user plugin.
fields you are going to add just write them in to update files -> plugins\hardiksatasiya\demotest\updates
1.0.1:
- 'Initialize plugin.'
1.0.2:
- 'Created table hardiksatasiya_demotest_'
- update_user_my_custom_add_seen.php
update_user_my_custom_add_seen.php file
<?php namespace HardikSatasiya\DemoTest\Updates;
use Schema;
use October\Rain\Database\Updates\Migration;
class UpdateUserMyCustomAddSeen extends Migration
{
public function up()
{
Schema::table('users', function($table)
{
$table->timestamp('last_seen')->nullable();
});
}
public function down()
{
Schema::table('users', function($table)
{
$table->dropColumn('last_seen');
});
}
}
this example shows how to add last_seen field in users table
now just use extend api to add field in form extendFormFields https://octobercms.com/docs/backend/forms#extend-form-fields
now test them on development server if all is working fine.
then only put that plugin in plugins directory
directory structure => plugins \ < author name > \ < plugin name >
now in live system - from backend logout and login
i guess this will do all required stuff.
make sure you test plugin well in development. to avoid unwanted problems
if any doubts please comment.

Laravel DatabaseTransactions for PHPunit have no effect

Writing tests for an existing API, there are many cases where the database has been modified. What I have been doing is something as follows:
public function testPut()
{
//setup
/*Copy an existing record and take its data as an array.
* the function being tested will take an array of data
* and create a new record. Using existing data guarantees
* the data is valid.
*/
$customerObj = Customer::getInstance(); //regular instantiation disabled in this api
$cust = ArCust::first()->toArray();
$oldNum = $cust['CUST_NO'];
unset($cust['CUST_NO']);
$custNo = rand(1, 9999999999999);
//test
/*put() creates a new customer record in the database
and returns the object.
*/
$this->assertInternalType('object', $customerObj->put($custNo, $cust));
//cleanup
/*manually remove the newly created record.
*/
ArCust::whereNam($cust['NAM'])->whereNotIn('CUST_NO', [$oldNum])->delete();
}
I am now running into instances where the API creates or updates many tables based on foreign keys. It would take far too much time to go through and manually reset each table.
The DatabaseTransaction trait provided by Laravel is supposed to take care of resetting everything for you. However, when I use it, I still find the test-created records in the database.
Here is how I have used it:
class CustomerTest extends TestCase
{
use DatabaseTransactions;
public function testPut()
{
//setup
$customerObj = Customer::getInstance();
$cust = ArCust::first()->toArray();
$oldNum = $cust['CUST_NO'];
unset($cust['CUST_NO']);
$custNo = rand(1, 9999999999999);
//test
$this->assertInternalType('object', $customerObj->put($custNo, $cust));
}
}
Am I using this incorrectly? Getting DatabaseTransactions to work correctly will save an incredible amount of time, as well as make the testes more readable to other people.
The issue was that we had multiple database connections defined in config > database.
In the database.php conf file, I changed the default connection to the correct database using its name as defined in the setup:
$connection = 'counterpoint';
and DatabaseTransactions now works.
This next step to this solution is to direct the connection of each test to the appropriate database rather than change the global connection.

How to rewrite field in Laravel?

I tried to rewrite a primary key in laravel like as:
public function setIdAttribute($value)
{
$this->attributes['id'] = $value; // or instead $value $this->attributes['idCity']
}
So I need to replace value of id field on value of idCity field
Rename a columns you should create a new migration
To create migration for this change write on console
php artisan make:migration swapKeyId
then go to database->migrations->...swapkey....php
in method called function up() write the code below but replace your table name in my case i use users
Schema::table('users', function ($table) {
$table->renameColumn('id', 'userId');
});
now its time to push migrates to database
php artisan migrate
and its done. this method is renamin it via laravel, also you can change it directly to the database(MySQL,MariaDB,SQL Server etc)
Setting an attribute in your model to define how php should store a value is something entirely different from creating a primary key in MySQL. Setup your migrations following the documentation and there isn't a lot that can go wrong:
Migrations in Laravel 5.2

Resources