Kio*_*iow 3 mass-assignment laravel
当涉及到 laravel 批量分配时,我有点困惑。
我知道我可以使用以下方法保护字段:
protected $fillable = [
'username', 'email', 'password'
];
Run Code Online (Sandbox Code Playgroud)
并在此处受到保护:
$flight = App\Flight::create(Input:all);
or
$flight->fill(['name' => 'Flight 22']);
Run Code Online (Sandbox Code Playgroud)
但我只创建或更新这样的模型:
public function createUser(NewUserRequest $request, User $newUser)
{
$newUser->insertUser($request);
}
Run Code Online (Sandbox Code Playgroud)
insertUser看起来像这样:
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;
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我总是选择要插入的字段以及应插入的数据。那么$fillable当我不使用create()orfill()方法时,我真的需要设置我的吗?
批量赋值保护的目的是保护直接从用户输入获取模型属性的开发人员,例如:
Example::create($request->input());
Run Code Online (Sandbox Code Playgroud)
如果没有批量分配保护,了解底层应用程序架构的用户可以将值注入到他们不希望访问的字段中,例如,如果您的 User 字段有一个is_admin值,他们可以将其更改is_admin为1而不是0。
质量分配保护只用unsanitized用户输入和质量分配工作的保护时,默认质量分配时,才会启用时需要。您有 3 个安全应用程序选项:
$fillable$user->name = 'John Doe'禁用批量分配保护,不要从用户输入中批量分配,例如:
protected $guarded = [];
Example::create($request->only('name', 'age'));
Example::create(['name' => $request->name, 'age' => $request->age]);
Run Code Online (Sandbox Code Playgroud)您不需要在示例中禁用批量分配保护,因为您不是批量分配值,而是单独为每个属性分配一个值。您可以通过问自己“我是否传入了一组属性及其值?”来确定您是否正在使用批量赋值。
您可以在Eloquent 文档 中了解有关批量分配的更多信息。