31
loading...
This website collects cookies to deliver better user experience
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateSettingsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('settings', function (Blueprint $table) {
$table->id();
$table->string('key')->unique();
$table->text('value');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('settings');
}
}
key => value
combination.saved
event, because the saving/saved events will dispatch when a model is created or updated.This is tested in Laravel 8 application, but I believe it will work well from Laravel version 5.5 and up.
<?php
namespace App\Models;
use Illuminate\Support\Facades\File;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
use HasFactory;
/**
* The attributes that aren't mass assignable.
*
* @var array
*/
protected $guarded = [];
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::saved(function () {
$settings = static::pluck('value', 'key')->toArray();
$parsable_string = var_export($settings, true);
$content = "<?php return {$parsable_string};";
File::put(config_path('app_settings.php'), $content);
});
}
//...
}
pluck
method we retrieve an Illuminate\Support\Collection
instance containing the keys/values.toArray
method converts the collection into a plain PHP array
.var_export
returns a parsable string representation of the $settings
variable.config_path
function to generate a fully qualified path to a file within the application’s configuration directory, a file I named app_settings.php. You are free to change it to whatever suits you best.put
method is used to store file contents on the disk./config/app_settings.php
to .gitignore
file.