gpt4 book ai didi

Laravel 在逐个字段设置时是否需要担心批量分配

转载 作者:行者123 更新时间:2023-12-04 16:45:31 24 4
gpt4 key购买 nike

当涉及到 laravel 批量分配时,我有点困惑。

我知道我可以使用以下方法保护字段:

protected $fillable = [
'username', 'email', 'password'
];

并在此处受到保护:
$flight = App\Flight::create(Input:all);

or

$flight->fill(['name' => 'Flight 22']);

但是我 只有像这样创建或更新模型:
public function createUser(NewUserRequest $request, User $newUser)
{

$newUser->insertUser($request);

}

插入用户 看起来像这样:
public function insertUser($request)
{
$newUser = $this;
$newUser->user_type = (int) $request->input('user_type');
$newUser->username = $request->input('username');
$newUser->email = $request->input('email');
if ($request->filled('password')) {
$newUser->password = bcrypt($request->input('password'));
}
if ($request->filled('facebook_id')) {
$newUser->facebook_id = $request->input('facebook_id');
}
$newUser->save();

return $newUser;
}

如您所见,我总是选择要插入的字段以及应插入的数据。所以我真的需要设置我的 $fillable当我不使用 create()fill()方法?

最佳答案

批量分配保护的目的是保护直接从用户输入获取模型属性的开发人员,例如:

Example::create($request->input());

如果没有批量分配保护,了解底层应用程序架构的用户可以将值注入(inject)到他们不希望访问的字段中,例如,如果您的用户字段具有 is_admin他们可以改变他们的值(value) is_admin1而不是 0 .

仅在处理未清理的用户输入时才需要批量分配保护,并且仅在批量分配时默认启用批量分配保护。您有 3 个安全应用程序选项:
  • 使用批量分配并将 $fillable 中的每个属性列入白名单
  • 单独赋值,因此没有批量赋值保护,例如:$user->name = 'John Doe'
  • 禁用批量分配保护,不要从用户输入中批量分配,例如:
    protected $guarded = [];

    Example::create($request->only('name', 'age'));

    Example::create(['name' => $request->name, 'age' => $request->age]);

  • 您不需要在示例中禁用批量分配保护,因为您不是批量分配值,而是为每个属性单独分配一个值。您可以通过问自己“我是否传入了一组属性及其值?”来确定您是否正在使用批量赋值。

    您可以在 Eloquent documentation 中了解有关批量分配的更多信息.

    关于Laravel 在逐个字段设置时是否需要担心批量分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49806180/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com