Laravel 将空插入表单并将空值插入数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53511239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Inserting Empty to Form and Null Value to Database
提问by
How to insert an empty value to input text and set it to null to the database, as I do this I'm having an error because the rows of the database do not have a value. How can I do this without an error?
如何插入空值以输入文本并将其设置为数据库的空值,因为我这样做我有一个错误,因为数据库的行没有值。我怎样才能做到这一点而不会出错?
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null (SQL: insert into
awards
(title
,description
,awards_image
,updated_at
,created_at
) values (, , a:0:{}, 2018-11-28 10:29:35, 2018-11-28 10:29:35))
SQLSTATE[23000]: 完整性约束违规:1048 列 'title' 不能为空(SQL:插入
awards
(title
,description
,awards_image
,updated_at
,created_at
) values (, , a:0:{}, 2018-11-28 10:29:35, 2018-11-28 10:29:35))
EDIT
编辑
<?php
foreach ($awards as $key => $values) {
$awardsContent = new Award;
$awardsContent->title = $request->title[$key];
$awardsContent->description = $request->description[$key];
$awardsContent->awards_image = $values;
$awardsContent->save();
}
Controller
控制器
public function store(Request $request)
{
$this->validate($request, [
'title' => 'nullable',
'description' => 'nullable',
'awards_image.*' => 'image|nullable|max:1999'
]);
$awards = [];
if ($request->has('awards_image')) {
foreach ($request->file('awards_image') as $key => $file) {
$filenameWithExt = $file->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
$extension = $file->getClientOriginalExtension();
$fileNameToStore = $filename . '_' . time() . '.' . $extension;
$path = $file->storeAs('public/awards_images', $fileNameToStore);
array_push($awards, $fileNameToStore);
}
$fileNameToStore = serialize($awards);
} else {
$fileNameToStore = 'noimage.jpg';
}
$awardsContent = new Award;
$awardsContent->title = $request->input('title');
$awardsContent->description = $request->input('description');
$awardsContent->awards_image = $fileNameToStore;
$awardsContent->save();
return redirect('/admin/airlineplus/awards')->with('success', 'Content Created');
}
回答by Sagar Gautam
You have to change your database migration schema like this
您必须像这样更改数据库迁移架构
$table->string('title')->nullable();
and then refresh your migration with this,
然后用这个刷新你的迁移,
php artisan migrate:refresh
回答by Thursday42
Your database doesn't currently allow the title column to be null. You can either change that field in the table to be nullable, or you can update your code to use an empty string if the value from the request is null.
您的数据库当前不允许标题列为空。您可以将表中的该字段更改为可为空,或者如果请求中的值为空,则您可以更新代码以使用空字符串。
$awardsContent->title = $request->filled('title') ? $request->get('title') : '';