简体   繁体   English

Laravel - 在 laravel model 中使用或不使用可填充?

[英]Laravel - USING or NOT USING fillable in laravel model?

I want to use this code: Model::update($request);我想使用这个代码: Model::update($request); , However all fields in the table might be modified by a malicious user so I change the $fillable in the model to modify only the ones that user can modify not others. , 但是表中的所有字段都可能被恶意用户修改,因此我将 model 中的$fillable fillable 更改为仅修改用户可以修改的字段,而不能修改其他字段。 But now the problem is that I can't modify it myself by own values.但现在的问题是我自己不能通过自己的价值观来修改它。

id  name  verified
1   Alex     0

if the data the malicious user sends inside $request is:如果恶意用户在$request中发送的数据是:

[
    'name' => 'ModifiedAlex',
    'verified' => 1,
]

so it will modify the table and get verified that is not good And when setting $fillable to only name:所以它会修改表并得到验证是不好的当设置$fillable为仅名称时:

$fillable = [
    'name'
];

then I myself can't modify that with Model::where('id', $userId)->update(['verified' => 1]) .然后我自己不能用Model::where('id', $userId)->update(['verified' => 1])修改它。

What to do then?那该怎么办? Use $fillable or not?是否使用$fillable

Keep using fillable and eloquent for the malicious users.继续为恶意用户使用可填充和 eloquent

You can use Query Builder to avoid the fillable for yourself.您可以使用查询生成器来避免自己fillable It doesn't check the fillable .:它不检查fillable的 .:

DB::table('users')->where('id', $userId)->update(['verified' => 1]); // update with verified.

You can update records by object您可以通过 object 更新记录

$user = \App\User::find(1);
$user->verified = 1;
$user->save();

Where user is giving data you can use Model::where('id', $userId)->update($request->except('_token')) so it avoids any other fields.在用户提供数据的地方,您可以使用Model::where('id', $userId)->update($request->except('_token'))以避免任何其他字段。

$request->except('_token') gives you all the post data except the _token index $request->except('_token')为您提供除_token索引之外的所有帖子数据

But for admin you can use save on object to update / create users但是对于管理员,您可以使用 object 上的save更新/创建用户

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM