If you want to use out-of-the-box Laravel you can create a model to assist you with that. In order for you to create a model, you can run php artisan make:model Setting
or you can create a model manually. Below is an example which you should place in a new file (Setting.php
) in the /App/Models directory.
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Setting extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'Settings';
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'option';
/**
* Indicates if the model's ID is auto-incrementing.
*
* @var bool
*/
public $incrementing = false;
/**
* The data type of the auto-incrementing ID.
*
* @var string
*/
protected $keyType = 'string';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['option', 'value'];
}
You can then create a controller by running the following command: php artisan make:controller SettingController --resource --model=Setting
. The command will automatically create a resource controller for the Setting model based on the Laravel documentation.
In your controller, you can request a certain value of one of your settings by using the following code:
// Retrieve a model by its primary key...
$site_name = Setting::find('site_name')->value;
Or you can request all settings listed in your database by using this line:
// Retrieve all settings
$settings = Setting::all();
You can further process the settings with code like this:
// Create a list of all options and associated values
foreach ($settings as $setting) {
echo $setting->option . ": " . $setting->value;
}
You can find way more information about Laravel models in the documentation and online.
I haven't tested the codes but they should work.
Update all options
If you want to update all options you should create a HTML form like this one:
<form action="{{ route('setting.update') }}" method="POST">
@csrf
@method('PUT')
@foreach ($settings as $setting)
<label>{{ $setting->option }}</label>
<input type="text" name="{{ $setting->option }}" value="{{ $setting->value }}"/>
@endforeach
<input type="submit">
</form>
In your update() function in your controller you can then update all values by using the following code:
public function update(Request $request)
{
$settings = Setting::update($request->all());
}
I'm not sure if the update will work correctly with the code above so please let me know :)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…