Laravel 7 错误 - SQLSTATE [23000]:完整性约束违规:1048 列 'first_name' 不能为空

Posted

技术标签:

【中文标题】Laravel 7 错误 - SQLSTATE [23000]:完整性约束违规:1048 列 \'first_name\' 不能为空【英文标题】:Laravel 7 error - SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'first_name' cannot be nullLaravel 7 错误 - SQLSTATE [23000]:完整性约束违规:1048 列 'first_name' 不能为空 【发布时间】:2021-01-13 21:20:22 【问题描述】:

我正在尝试使用 Jquery Ajax 将表单数据提交到数据库,但我收到错误消息。输入字段的值似乎在Controller端没有收到,这就是为什么它没有发送到数据库进行存储。以下是我打算做什么的简要说明:-

    用户选择注册。

    注册页面打开(我们称之为Form 1

    用户在Form 1

    中填写数据

    如果出现空字段或无效格式等错误信息,会显示在Form 1

    的相应输入字段下方

    如果没有错误消息,则用户将被重定向到一个新表单(我们称之为 Form 2),其中包含 Form 1 中的所有预填充数据。

    如果用户点击“提交”,则数据(来自Form 2)使用 Ajax 发送到控制器,并存储在带有 Sweet Alert 的数据库中留言

但是,数据似乎没有正确发送到控制器,这就是我收到错误的原因。

代码如下

Form 2

之刃
<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">

      <!-- CSRF Token Meta Added -->
      <meta name="csrf-token" content=" csrf_token() ">

    <!-- Optional javascript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>

    <!-- Ajax script -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>


    <!-- Sweet Alert -->
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>


    </head>
  <body>
    <!-- Navigation Bar --> 
   <div class="container-fluid">
  <div class="row">
    <div class="col">
      <nav class="navbar navbar-expand-sm bg-dark navbar-dark navbar-fixed-top">
  <a class="navbar-brand" href="index">User Info</a>
  <ul class="navbar-nav">
    <li class="nav-item active">
      <a class="nav-link" href="#">Home</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">Features</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">About Us</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">Contact Us</a>
    </li>

    
  </ul>
  <ul class="nav navbar-nav navbar-right ">
  <li class="nav-item"><a class="nav-link" href="new_user"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
      <li class="nav-item"><a class="nav-link" href="login"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
    </ul>

  
</nav>
    </div>
  </div>

 <div class="text-center pt-3">
<p style="color:red">For safety,Do Not hit the back button or refresh the page</p>
<p style="color:red">Use the buttons given in the form below</p>
</div>

<form class="form-group" id="new_user_form" method="post"  autocomplete="off">
 <div class="row  m-5 p-5 bg-warning text-white">
     <div class="col">
<div class="form-group">
  @csrf
  <input type="hidden" name="_token" id="csrf" value="Session::token()">
 <label for="fname">First Name:</label>
  <input type="text" class="form-control" id="first_name" name="first_name" value="$first_name" readonly >
</div>
<div class="form-group">
 <label for="lname">Last Name:</label>
  <input type="text" class="form-control" name="last_name" id="last_name" value="$last_name" readonly>
</div>
<div class="form-group">
 <label for="email">Email/Username:</label>
  <input type="text" class="form-control" name="email" id="email" value="$email" readonly>
</div>
<div class="form-group">
  <label for="pwd">Password:</label>
  <input type="password" class="form-control" name="password" id="password" value="$password" readonly>
</div>

  <div class="form-group">
 <label for="mobno">Mobile Number:</label>
  <input type="text" class="form-control" name="mobno" id="mobno" value="$mobno" readonly>
</div>
<div class="form-group">
 <label for="dob">Date of Birth(in YYYY-MM-DD):</label>
  <input type="text" class="form-control" name="dob" id="dob" value="$dob" readonly>
</div>

<div class="form-group">
  <label for="gender">Gender:</label>
   <input type="text" class="form-control" name="gender" id="gender" value="$gender" readonly>

 </div>
  <div class="form-group">
  <label for="address">Address:</label>
  <textarea class="form-control" rows="5" name="address" id="address" readonly>$address</textarea>
</div>

<div class="form-group">
<label for="country">Country:</label>
 <input name="country" class="form-control" id="countrylist" value="$country" readonly>
</div>

 <div class="form-group">
 <label for="dt">Date and Time of Submission:</label>
  <input type="text" class="form-control" name="dt" id="dt" value=@php date_default_timezone_set("Asia/Kolkata"); echo date("Y-m-d,H:i:s ") @endphp readonly>
</div>
<div class="form-group text-center">
<!-- <a href="url('recheck_form')"/><button type="submit" class="btn btn-primary mb-2 text-center" onclick="store_using_ajax()">Submit</button> -->
<button type="submit" class="btn btn-primary mb-2 text-center" id="submit_form">Submit</button>
</div>
<div class="form-group text-center ">
<button type="button" class="btn btn-danger"><a href="new_user">Cancel</a></button>
<button type="button" class="btn btn-warning "><a href="">Edit</a></button>
</div>

</div>

</div>

</form>

</div>   
 


<script type="text/javascript">
   $(document).ready(function()
     $('#submit_form').click(function (e)

       e.preventDefault(); //Prevents the form from submitting

          // var  first_name      =    $('#first_name').val(),
          // var last_name        =    $('#last_name').val(),
          // var email            =    $('#email').val(),
          // var password         =    $('#password').val(),
          // var mobno            =    $('#mobno').val(),
          // var dob              =    $('#dob').val(),
          // var gender           =    $('#gender').val(),
          // var address          =    $('#address').val(),
          // var dt               =    $('#dt').val(),
 
       /*Ajax Request Header setup*/
   $.ajaxSetup(
      headers: 
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      
      );  

     $.ajax(
       type:'POST',
       url: "submit-form" ,
       cache: false,
       processData: false,
         contentType: false,
       
        // data: $('#new_user_form').serialize(),
        data: 

           // _token             :    $("#csrf").val(),
           // first_name         :    first_name,  
           // last_name          :    last_name,  
           // email              :    email  ,
           // password           :    password  ,  
           // mobno              :    mobno ,  
           // dob                :    dob  ,
           // gender             :    gender  ,
           // address            :    address   ,  
           // dt                 :    dt   ,  
            

          '_token'             :    $("#csrf").val(),
         'first_name'         :    $('#first_name').val(),
          'last_name'         :    $('#last_name').val(),
          'email'             :    $('#email').val(),
          'password'           :    $('#password').val(),
          'mobno'              :    $('#mobno').val(),
          'dob'                 :     $('#dob').val(),
          'gender'              :     $('#gender').val(),
          'address'              :       $('#address').val(),
          'dt'                  :        $('#dt').val(),

        ,
        dataType: 'JSON',

       success:function(data)
            swal(
         title: "Form Submitted Successfully!",
         text: "New User Registered !",
         icon: "success",
         button: "Okay",
         timer: 1500
       )
            setTimeout(function() window.location = "login-page"; , 2000);
             


       ,
       error: function(data)
       swal(
             title: "Error in submitting form",
             text: "Please try again later! ",
             icon: "warning",
            button: "Okay",
            );
            
             
  );

   );
     );

 </script>

</body>
</html>

Form 2

的控制器代码
<?php

namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Database\Eloquent\Model;
use App\Newuser;

class NewUserRegnController extends Controller

       public function submitNewRegn(Request $request)
     
    $r_first_name           =   $request->first_name;
    $r_last_name            =   $request->last_name;
    $r_email                =   $request->email;
    $r_password             =   Hash::make($request->password, [
                                     'memory' => '1024',
                                     'time' =>  '2',
                                     'threar' =>  '2',
                                    ]);
    // $confirm_password    =   $request->confirm_password;
    $r_mobno                =   $request->mobno;
    $r_dob              =   $request->dob;
    $r_gender           =   $request->gender;
    $r_address          =   $request->address;
    $r_country          =   $request->country;
    date_default_timezone_set("Asia/Kolkata"); 
    $r_time             =   date("Y-m-d,H:i:s ");

      // $users = new Newuser();
      // $users->first_name = $first_name; 
      // $users->last_name = $last_name; 
      // $users->email = $email; 
      // $users->password = $password; 
      // $users->mobno = $mobno; 
      // $users->dob = $dob; 
      // $users->gender = $gender; 
      // $users->address = $address; 
      // $users->country = $country; 
      // $users->TIME_STAMP = $time; 

      // $users->save();


    $act =  "INSERT";
    DB::select('CALL my_stored_procedures(?,?,?,?,?,?,?,?,?,?,?,?)', array($act,0,$r_first_name,$r_last_name,$r_email,$r_password,$r_mobno,$r_dob,   $r_gender,$r_address,$r_country,$r_time));
   

  return response()->json(
            [
                'success' => true,
                'message' => 'Data inserted successfully'
            ]
        );


      


虽然我没有在任何地方使用过 _token,但我将逐步添加会话和 cookie,因为我是 Laravel 新手。所以,别介意。

【问题讨论】:

您正在使用模型,您是否在模型的 fillable 属性上添加了所有列名? 在后端代码中使用数据验证来避免此类问题。 我正在使用模型测试代码,但现在我没有。 @sta @iamab.in 是的。我没有在刀片中使用数据验证 Fillable 可让您指定模型中可以批量分配的字段。让我们以上面的例子为例,您可以通过在模型中添加特殊变量 $fillable 来实现。所以在模型中:protected $fillable = ['first_name', 'last_name']; 【参考方案1】:

步骤 1) 我建议看看控制器端收到的实际请求; dd($request) 作为submitNewRegn 的第一行

步骤 2) (如 cmets 中的 iamab.in 所述)继续验证提交表单的内容,验证方法概述 here。验证应与数据库表中的排版匹配(查看您的迁移文件!)

这看起来像这样:

request()->validate([
                'first_name' => 'required|min:3',
                'last_name' => 'required|min:2',
            ]);

步骤 3) 存储在数据库中的正确表中

这可能看起来像这样:

$user= User::create($attributes);

【讨论】:

以上是关于Laravel 7 错误 - SQLSTATE [23000]:完整性约束违规:1048 列 'first_name' 不能为空的主要内容,如果未能解决你的问题,请参考以下文章

SQLSTATE[HY000]:一般错误:1215 无法添加外键约束 [Laravel 7.0]

Laravel 7 SQLSTATE [HY000] [2002] 连接被拒绝

Laravel 7 错误 - SQLSTATE [23000]:完整性约束违规:1048 列 'first_name' 不能为空

SQLSTATE [23000]:完整性约束违规:1048 laravel 5.7

Laravel 5.7 迁移错误:SQLSTATE[HY000] [2002] No such file or directory

Laravel 7 SQLSTATE[HY000] [2002] 没有这样的文件或目录