我写了下面的代码,我该如何清理它?谁能帮我写得更好?

i write the below code , how can i cleaning it? can any one help me to write it better?

我在laravel中写了这段代码,谁能帮我写得更好?

 Setting::where('key' , 'online_course')->update(['value' => $request->get('online_course') ]);
    Setting::where('key' , 'read_item')->update(['value' => $request->get('read_item') ]);
    Setting::where('key' , 'comment_item')->update(['value' => $request->get('comment_item') ]);
    Setting::where('key' , 'rate_item')->update(['value' => $request->get('rate_item') ]);

一个可能的解决方案是使用 foreach 循环从 $request 对象中拉出 keysvalues

foreach ($request->only('online_course', 'read_item', 'comment_item', 'rate_item') as $key => $value) {
    Setting::where('key', $key)->update(['value', $value]);
}

可以 使用 $request->all()$request 对象中获取所有 keys 以进一步缩短它,但是如果您要这样做确保您有足够的评估和安全防护措施(例如批量分配),这样您就不会意外使用一些不需要的 $request 数据。

根据你的想法我写了这段代码

foreach ($request->except('_token' , '_method') as $key => $value){
        Setting::where('key' , $key)->update(['value' => $value]);
    }

但是这段代码可以正常工作

 foreach ($request->all() as $key => $value){
        Setting::where('key' , $key)->update(['value' => $value]);
    }