批量分配是发送一组数据的过程,这些数据将立即保存到指定的模型中。通常,您不需要将数据逐个保存在模型上,而是在一个进程中保存。
批量分配是好的,但背后存在一定的安全问题。如果有人将值传递给模型并且没有保护,他们肯定可以修改包括 ID 在内的所有字段。这不好。
假设您有 'students' 表,其中包含字段 “student_type, first_name, last_name”。您可能想要批量分配“first_name, last_name”,但您想要以保护 student_type 不被直接更改。这就是 fillable 和 guarded 发生的地方。
Fillable 可让您指定模型中可批量分配的字段,您可以通过向模型添加特殊变量 $fillable 来实现。所以在模型中:
class Student extends Model {
protected $fillable = ['first_name', 'last_name']; //only the field names inside the array can be mass-assign
}
'student_type'不包括在内,这意味着他们被豁免了。
Guarded 是 fillable 的反面。如果 fillable 指定要批量分配的字段,guarded 指定不可批量分配的字段。所以在模型中:
class Student extends Model {
protected $guarded = ['student_type']; //the field name inside the array is not mass-assignable
}
您应该使用 $fillable 或 $guarded - 不能同时使用。
更多详情请打开链接:-Mass Assignment