【问题标题】:SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: posts.titleSQLSTATE [23000]:违反完整性约束:19 NOT NULL 约束失败:posts.title
【发布时间】:2020-01-28 14:59:54
【问题描述】:

Laravel 新手,试图让用户能够创建帖子。当我单击提交时,我收到此错误:

SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: posts.title (SQL: insert into "posts" ("user_id", "updated_at", "created_at") values (1, 2020-01-23 04:19:50, 2020-01-23 04:19:50))

我见过类似的问题,但没有一个得到很好的答案。 这是我的模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $gaurded = [];

    protected $fillable = ['title', 'thought', 'image', 'url'];

    public function user(){ 

        return $this->belongsTo(User::class);
    }
}

create.blade.php:

@extends('layouts.app')

@section('content')

<body>


    <div class="container">

        <form action="/p" enctype="multipart/form-data" method="post">

            @csrf

        <div class="row">
            <div class="col-8 offset-2">
                <h1>New Post:</h1>
                <div class="form-group row">
                            <label for="title" class="col-md-4 col-form-label">Title</label>


                                <input id="title" name="title" type="text" class="form-control @error('title') is-invalid @enderror" title="title" value="{{ old('title') }}" required autocomplete="title" autofocus>


                            </div>

            </div>
        </div>

              <div class="row">
             <div class="col-8 offset-2">

                <div class="form-group row">
            <label for="thoughts" class="col-md-4 col-form-label">Thoughts</label>
                    <textarea type="text" class="form-control @error('thoughts') is-invalid @enderror" id="thoughts" name="thoughts"></textarea>  
               @error('file')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                 </div>
            </div>
        </div>

        <div class="row">
             <div class="col-8 offset-2">

                <div class="form-group row">
            <label for="image" class="col-md-4 col-form-label">Image</label>
            <input type="file" class="form-control-file" id="image" name="image">  
               @error('file')
                                    <span class="invalid-feedback" role="alert">
                                        <strong>{{ $message }}</strong>
                                    </span>
                                @enderror
                 </div>
            </div>
        </div> 



           <div class="row pt-4">
             <div class="col-8 offset-2">

                <div class="form-group row">
                    <button class="btn btn-primary">Add post</button>
                 </div>
               </div>
            </div>

        </form>

    </div>

</body>


@endsection

PostsController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostsController extends Controller
{
    public function create(){

        return view('posts.create');
    }

    public function store(){

        $data = request()->validate([
            'title',
            'thought',
            'image',
            'url'
        ]);

        auth()->user()->posts()->create($data);

        dd(request()->all());
    }
}

最后是表格:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('user_id');
            $table->text('title');
            $table->text('thought');
            $table->string('url')->nullable();
            $table->string('image')->nullable();
            $table->timestamps();

            $table->index('user_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

任何建议都会很棒。如果您需要任何其他信息,请告诉我。

【问题讨论】:

  • 错误说明了一切。帖子标题不能是null。帖子的创建大概在posts.create。检查代码以在此处插入新帖子。

标签: php sql laravel


【解决方案1】:

您缺少用于标题输入的 name="title"

//...
<input id="title" name="title" type="text" class="form-control @error('title') is-invalid @enderror" title="title" value="{{ old('title') }}" required autocomplete="title" autofocus>

更新

您还缺少验证规则

查看docs

//...
$validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'thought' => 'required',
        'image' => 'required|image',
        'url' => 'required|url'
]);

auth()->user()->posts()->create($validatedData);

【讨论】:

  • 我添加了这个,我得到了同样的错误。我更新了问题以显示我添加它的位置。感谢您的回复。
  • 您必须将 'title' 添加到 $fillable 数组中:protected $fillable = [ 'title', .... ];
  • 在哪里添加?
  • @ColePerry 在您的 Post 模型检查文档中laravel.com/docs/5.8/eloquent#mass-assignment
  • 我添加了它,并使其他输入也可填充。我编辑了我的问题以显示代码,但错误仍然存​​在。
【解决方案2】:

你可以通过两种类型来解决。

  1. 你可以在数据库中设置空值NULL(是)

  2. 使用 name="title"

【讨论】:

  • 我添加了 name="title" 并且我得到了同样的错误。我更新了问题以显示我添加它的位置。另外,我不希望标题能够为空,因此将其设置为非空。感谢您的回复。
猜你喜欢
  • 2018-03-20
  • 2021-06-10
  • 2021-03-24
  • 2020-01-28
  • 2020-12-28
  • 2021-01-26
  • 2020-09-17
  • 2014-08-18
相关资源
最近更新 更多