laravel在表单中插入空值,在数据库中插入空值

wvyml7n5  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(398)

如何插入一个空值来输入文本并将其设置为null到数据库中,当我这样做时,我遇到了一个错误,因为数据库的行没有值。我怎样才能做到不出错呢?
sqlstate[23000]:完整性约束冲突:1048列“title”不能为null(sql:insert-into) awards ( title , description , awards_image , updated_at , created_at )值(,a:0:{},2018-11-28 10:29:35,2018-11-28 10:29:35))
编辑

<?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();
}

控制器

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');
}
bybem2ql

bybem2ql1#

您必须像这样更改数据库迁移模式

$table->string('title')->nullable();

然后用这个刷新你的迁移,

php artisan migrate:refresh
crcmnpdw

crcmnpdw2#

您的数据库当前不允许标题列为空。您可以将表中的字段更改为可为null,或者如果请求中的值为null,则可以更新代码以使用空字符串。

$awardsContent->title = $request->filled('title') ? $request->get('title') : '';

相关问题