抱歉,是否在其他地方都提出了这个问题,但我到处搜索过但找不到答案。好吧,当我尝试从请求中获取变量时,我在Laravel 5.0上遇到了这个问题,我在生产服务器上获取了空值,但在开发服务器上获取了空字符串。该值在请求中不存在,即,提交表单时该字段为空。例如。
// ProductController
public function store(Request $request) {
// this field is actually empty in the submitted form
$price = $request->price;
// when it gets to the server this is how this value looks like :
// $price in production server : null
// $price in development server : ''
}
当我尝试将对象保存到数据库时
Product::save($request->only('name', 'price'));
我收到此错误(仅在生产服务器上)
SQLSTATE [23000]:违反完整性约束:1048列“价格”
不能为空
注意,价格列在mysql表上具有“默认0”
为什么会这样呢?
更新:
一直以来,我都认为如果不存在该字段,则request-> input()方法将返回空字符串('')。但只知道我看着laravel来源就可以看到:
public function input($key = null, $default = null)
{
$input = $this->getInputSource()->all() + $this->query->all();
return array_get($input, $key, $default);
}
在这里它返回null作为默认值。那为什么我在开发服务器上得到空字符串?
最佳答案
发生这种情况是因为如果您未定义任何内容,则mysql会插入默认值。在这种情况下,Laravel发送一个值,该值为null。您不应使用Request::only
,而应使用数组。
明确明确总是好事,它使您的代码可读性和一致性。