【问题标题】:Laravel 8: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be nullLaravel 8:SQLSTATE [23000]:违反完整性约束:1048 列“标题”不能为空
【发布时间】:2021-02-09 11:23:10
【问题描述】:

我正在使用 Laravel 8,我制作了一个简单的表单,如下所示:

<form action="/create" method="POST">
    @csrf 
    <label for="title">Title:</label>
    <input type="text" name="title"></br>
    <label for="body">Body:</label>
    <textarea name="body" cols="30" rows="10"></textarea>
    <button>Send</button>
</form>

然后在web.php,我把这个:

Route::post('/create',function(){
    $validator = Validator::make(request()->all(),[
        'title' => 'required',
        'body' => 'required'
    ]);
    Article::create([
        'title' => request('title'),
        'body' => request('body')
    ]);
    return redirect('/create');
});

但只要我提交表单,我就会看到消息:

照亮\数据库\查询异常 SQLSTATE[23000]:完整性约束违规:1048 列“标题”不能为空(SQL:插入articles(title,body,updated_at,created_at)值(?,?,2020- 10-27 07:36:47, 2020-10-27 07:36:47)))

我知道这意味着表中有一列不能为 NULL。但正如你在代码中看到的,我确定了验证,所以如果输入没有填写,应该会弹出 Required 消息,但它没有并且再次出现错误消息。

这也是table的迁移:

public function up()
{
    Schema::create('articles', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('body');
        $table->timestamps();
    });
}

所以如果你知道,我该如何解决这个问题,请告诉我,我真的很感激......

提前致谢。

【问题讨论】:

  • 尝试dd(request()-&gt;all()) 查看所有帖子参数是否存在
  • array:3 [▼ "_token" =&gt; "WupvBPXbBaL1lxOrOMRSq5weZH654tKNh2ewwJZS" "title" =&gt; null "body" =&gt; null ]
  • 所以,这就是您的代码不起作用的原因。我的建议; 1) 尽量不要使用基于闭包的请求处理程序。使用控制器。
  • 那么为什么验证不起作用,所以用户必须填写表格
  • 2) 使用$request-&gt;validate() 而不是创建新的验证器。

标签: php mysql laravel laravel-8


【解决方案1】:
Route::post('/create',function(){
    $validator = Validator::make(request()->all(),[
        'title' => 'required',
        'body' => 'required'
    ]);
    Article::create([
        'title' => request()->input('title'),
        'body' => request()->input('body')
    ]);
    return redirect('/create');
});

【讨论】:

  • 你在文章文件中写了可填充的功能吗?
  • 受保护的 $fillable = [ 'title', 'body' ];
  • Validator::make($request->all(), [ 'title' => 'required', 'body' => 'required', ])->validate();跨度>
  • 请在您的答案中添加一些解释,以便其他人可以从中学习
【解决方案2】:

如果您手动创建验证器实例,您必须自己处理失败的验证。您可以使用$validator-&gt;fails() 检查验证是否失败。我会改用$request-&gt;validate(),所以 Laravel 会自动处理失败的验证。

Manually Creating Validators:

如果您不想在请求上使用validate 方法,您可以 使用 Validator facade 手动创建验证器实例。这 门面上的make 方法生成一个新的验证器实例:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PostController extends Controller
{
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('post/create')
                        ->withErrors($validator)
                        ->withInput();
        }

        // Store the blog post...
    }
}

检查请求验证是否失败后,您可以使用 withErrors 方法将错误消息闪现到会话。什么时候 使用此方法,$errors 变量将自动共享 重定向后的视图,让您轻松显示它们 回给用户。 withErrors 方法接受一个验证器,一个 MessageBag,或 PHP array。

$request->validate():

public function store(Request $request)
{
    $validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    // The blog post is valid...
}

现在我们准备用以下逻辑填充我们的 store 方法 validate 新博文。为此,我们将使用验证 Illuminate\Http\Request 对象提供的方法。如果 验证规则通过,您的代码将继续正常执行; 但是,如果验证失败,则会抛出异常并且 正确的错误响应将自动发送回用户。在 对于传统的 HTTP 请求,重定向响应将是 生成,同时会为 AJAX 请求发送 JSON 响应。

所以你的情况如下:

use Illuminate\Http\Request;
use App\Models\Article;

Route::post('/create', function (Request $request) {
    $validatedData = $request->validate([
        'title' => 'required',
        'body' => 'required',
    ]);

    Article::create($validatedData);

    return redirect('/create');
});

【讨论】:

    【解决方案3】:

    您正在创建一个 Validator 实例,但没有使用它验证数据。

        $validator = Validator::make(request()->all(),[
            'title' => 'required',
            'body' => 'required'
        ]);
        
        // Validates request data. If fails redirect to /create
        if ($validator->fails()) {
            return redirect('/create')
                ->withErrors($validator)
                ->withInput();
         }
        // Validation passed, create article.
        Article::create([
            'title' => request()->input('title'),
            'body' => request()->input('body')
        ]);
        return redirect('/create');
    

    也可以read about working with validation error messages 了解如何在/create 页面上显示错误消息。

    【讨论】:

      【解决方案4】:

      试试这个:

      Route::post('/create',function(){
      $validateData = request()->validate([
      'title' => 'required',
      'body' => 'required',
      ]);
      Article::create(request()->all());
      return redirect('/create');
      });
      

      【讨论】:

      • 请在您的答案中添加一些解释,以便其他人可以从中学习
      【解决方案5】:

      您需要在模型上指定 fillable 或 guarded 属性,因为所有 Eloquent 模型都默认防止批量赋值。

      您可以在模型使用的特征中看到这一点:

      trait GuardsAttributes
      {
          /**
           * The attributes that are mass assignable.
           *
           * @var array
           */
          protected $fillable = [];
      
          /**
           * The attributes that aren't mass assignable.
           *
           * @var array
           */
          protected $guarded = ['*'];
      
          // ...
      }
      

      所以你需要使字段可填写。

      class Article extends Model
      {
          protected $fillable = [
              'title',
              'body',
          ];
      }
      

      【讨论】:

        猜你喜欢
        • 2020-08-07
        • 2020-02-11
        • 2021-02-01
        • 2017-07-31
        • 2019-11-20
        • 2021-08-16
        • 2019-10-06
        • 2020-10-25
        • 2017-02-28
        相关资源
        最近更新 更多