更新Laravel模型中的非填充字段

更新Laravel模型中的非填充字段

本文介绍了更新Laravel模型中的非填充字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的User表,当您完成整个 php artisan make:auth 之类的东西时,默认表laravel附带了,我添加了一个布尔 system_admin 列,以及其他两个类似的列

I have my User table, the default table laravel comes with when you do the whole php artisan make:auth stuff, and I've added a boolean system_admin column, and a couple other similar columns

现在,当有人注册该站点时,我不想要恶意的人为了能够赋予自己正确的权利,所以我没有将该字段放在User.php模型文件的可填充数组中。

Now when someone registers to the site, I don't want a malicious person to be able to just give themselves that right, so I haven't put that field in the fillable array in the User.php model file.

然后的第一个问题:是出于正确原因的正确决定吗?

First question then: is that the right decision for the right reason?

但是现在我正在系统管理页面上进行操作,应该允许人们修改那样的属性,但是在我的路线上,只有SystemAdmins可以访问,我的代码看起来像这样:

But now I'm working on a system admin page, which should allow people to modify properties like that, but in my route, that's only accessible by SystemAdmins, I have code that looks like this:

public function updateUser($userId, Request $request) {
        $user = User::find($userId);
        $update = $request->all();
        $user->update($update);

当然,因为这些列不能可填充,该请求不适用于这些字段。

And of course, because those columns aren't fillable, this request doesn't work for those fields.

但我希望这样做,因为此特定路由受中间件保护,该中间件验证system_admin应该具有访问权限

But I want it to, because this particular route is protected by middleware that verifies a system_admin should have access to it.

那么我如何更新这些不可填充的列,而又不允许nonSysAdmins更新相同的列?

So how do I update these non-fillable columns, without allowing nonSysAdmins to update the same columns?

推荐答案

我使用lagbox答案提出了另一种解决方案,该解决方案遍历了我的路线中的每个更新变量键:

I used lagbox answer to come up with an alternative solution that goes over every updating variable key in my route:

public function updateUser($userId, Request $request) {
    $user = User::find($userId);
    $update = $request->all();
    foreach($update as $key => $value) {
        $user->$key = $value;
    }
    $user->save();

    $newUser = User::find($userId);
    return response()->json($newUser->toJson());
}

我希望这样做没有错。

这篇关于更新Laravel模型中的非填充字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 16:50