Add Site Settings to the blog and good lesson learned
I wanted to add a setting page for this blog so that I can dynamically change the Site Title and Site Description, instead of hard-coding it in the blade file.
This guy already covered a part of the process: https://medium.com/@tasneem.90.wahdan/laravel-settings-made-simple-how-to-save-and-handle-them-efficiently-dd082e192b01, then I build the SettingController by myself.
What is the issue?
Everything was straightforward until the step the update the data to the database. I was using this code to update the database table based on the validated attributes:
public function update(Request $request)
{
$validatedAttrs = request()->validate(
[
'site_title' => 'required|min:5',
'site_description' => 'required'
]
);
foreach ($validatedAttrs as $key => $value) {
Setting::updateOrCreate(
['key' => $key],
['value' => $value]
);
}
return redirect()->route('admin.setting.edit')->with('success', 'Site setting updated successfully!');
}
Looks good, right?
NO!!! IT'S NOT!
Somehow the settings table is not updated at all. I consulted with ChatGPT, then Claude, then Grok and all suggested the same way: using updateOrCreate
Setting::updateOrCreate(
['key' => $key],
['value' => $value]
);
It was not working AT ALL!
I keep digging in desperate and finally figure out a way to update the database, using the direct method instead of using Eloquent ORM
DB::table('settings')->where('key', $key)->update(['value' => $value]);
Why?
The settings table was setup using this
Schema::create('settings', function (Blueprint $table) {
$table->string('key')->unique();
$table->text('value');
$table->timestamps();
});
It does not have id column, so it seems Eloquent ORM get some difficulty when running updateOrCreate() method.
Meanwhile, DB::table('settings') interacts directly with the database, so there is not issue.
Solution
For now, the easiest way for me is the update the migration file, adding column id
Schema::create('settings', function (Blueprint $table) {
$table->id();
$table->string('key')->unique();
$table->text('value');
$table->timestamps();
});
Drop the settings table, and re-create again using php artisan migrate
This is a good lesson for a beginner!