【问题标题】:Laravel Inserting Empty to Form and Null Value to DatabaseLaravel 将空值插入表单并将空值插入数据库
【发布时间】:2019-04-29 21:02:07
【问题描述】:

如何插入一个空值来输入文本并将其设置为空到数据库,因为我这样做我有一个错误,因为数据库的行没有值。我怎样才能做到这一点而不会出错?

SQLSTATE[23000]:违反完整性约束:1048 列“标题” 不能为空(SQL:插入awardstitledescriptionawards_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');
}

【问题讨论】:

  • 允许您的列接受空值,因为您的代码可能允许传递与列条件相矛盾的空值。

标签: php mysql laravel laravel-5 null


【解决方案1】:

您必须像这样更改数据库迁移架构

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

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

php artisan migrate:refresh

【讨论】:

  • @SummerWinter 当然
  • 兄弟,当我刷新时,我在数据库中的所有数据都消失了:(
  • 为了进行更改,您需要刷新数据库。对不起,我不知道你对上面的命令不熟悉
  • 没关系,先生,您能回答我上面编辑的代码吗,好像其他答案不起作用
【解决方案2】:

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

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

【讨论】:

  • 先生,您能否回答我上面的编辑代码,当我 foreach 循环代码时,您的答案不起作用,对不起,请回答帮助我,谢谢
  • 您应该能够针对这种情况做同样的事情。像这样的东西应该工作。 $awardsContent-&gt;title = !empty($request-&gt;title[$key]) ? $request-&gt;title[$key] : '';
猜你喜欢
  • 2019-04-29
  • 2018-11-10
  • 1970-01-01
  • 2022-09-27
  • 2017-09-11
  • 1970-01-01
  • 2015-12-03
  • 1970-01-01
  • 2017-04-04
相关资源
最近更新 更多