未使用 laravel 8 将数据插入数据库

Posted

技术标签:

【中文标题】未使用 laravel 8 将数据插入数据库【英文标题】:Data not inserted in database using laravel 8 【发布时间】:2021-08-14 14:36:29 【问题描述】:

我正在尝试将数据从表单模式保存到数据库。

所以,我正在使用以下代码:

控制器:

  public function store(Request $request)


   if ($files = $request->file('casting_photo'))

    
  
       $destinationPath = public_path('public/castingimages'); // upload path         
       $profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
       $files->move($destinationPath, $profileImage);
      
            $cast = new Casting;

            $cast -> casting_name= $request->input('casting_name');
            $cast -> casting_cin= $request->input('casting_cin');
            $cast -> casting_email= $request->input('casting_email');
            $cast -> casting_phone= $request->input('casting_phone');  
            $cast -> casting_gender= $request->input('casting_gender');
            $cast -> casting_address= $request->input('casting_address');
            $cast -> casting_city= $request->input('casting_city');
            $cast-> casting_photo=$profileImage;

              $cast->save();

    
    

查看:

   <x-app-layout>
    <div class="container-fluid">
      <div class="row">
        <div class="col app-col">
          <div class="mb-2">
            <h1>Castings</h1>

            <div class="top-right-button-container">
              <button type="button" data-target="#castingmodel" data-toggle="modal" class="btn btn-outline-primary btn-lg top-right-button  mr-1">Add New
</button>
              <div class="col-xl-6">
                <div id="result"></div>
              </div>
            </div>

            </div>
            <div class="separator mb-5"></div>
          </div>
       
      </div>
    </div>



 <div class="modal fade" id="castingmodel" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalContentLabel">New message</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            </div>
    <form method="post"  class="needs-validation tooltip-label-right" id="formcast" novalidate enctype="multipart/form-data">
         csrf_field() 
            <div class="modal-body">
                <input type="hidden" id="id_hidden" name="id" />

                <div class="form-group position-relative error-l-50">
                  <label>Name</label>
                  <input type="text" class="form-control" name ="casting_name" id="casting_name" >
                  <div class="invalid-tooltip">Name is required!</div>
                </div>
                <div class="form-group position-relative error-l-50">
                  <label>CIN</label>
                  <input type="text" class="form-control" name="casting_cin" id="casting_cin" required>
                  <div class="invalid-tooltip">CIN is required!</div>
                </div>
                <div class="form-group position-relative error-l-50">
                  <label>EMAIL</label>
                  <input type="text" class="form-control" rows="2" name="casting_email" required>
                  <div class="invalid-tooltip">EMAIL is required!</div>
                </div>
                <div class="form-group position-relative error-l-50">
                  <label>PHONE</label>
                  <input type="number" class="form-control" rows="2" name="casting_phone" required>
                  <div class="invalid-tooltip">PHONE is required!</div>
                </div>
                <div class="form-group position-relative">
                  <label>Radio</label>
                  <div>
                    <div class="custom-control custom-radio">
                      <input type="radio" id="jQueryCustomRadio1" name="casting_gender"  class="custom-control-input" required value="homme">
                      <label class="custom-control-label" for="jQueryCustomRadio1">Homme</label>
                    </div>
                    <div class="custom-control custom-radio">
                      <input type="radio" id="jQueryCustomRadio2" name="casting_gender" class="custom-control-input" required value="femme">
                      <label class="custom-control-label" for="jQueryCustomRadio2" >Femme</label>
                    </div>
                  </div>
                </div>
                <div class="form-group position-relative error-l-50">
                  <label>ADDRESS</label>
                  <input type="text" class="form-control" rows="2" name="casting_address" required>
                  <div class="invalid-tooltip">ADDRESS is required!</div>
                </div>
                <div class="form-group position-relative error-l-50">
                  <label>CITY</label>
                  <input type="text" class="form-control" rows="2" name="casting_city" required>
                  <div class="invalid-tooltip">CITY is required!</div>
                </div>
                <div class="input-group mb-3">
                  <div class="input-group-prepend">
                    <span class="input-group-text">Upload</span>
                  </div>
                  <div class="custom-file">
                    <input type="file" name="casting_photo" class="custom-file-input" id="inputGroupFile01">
                    <label class="custom-file-label" for="inputGroupFile01">Choose file</label>
                  </div>
                </div>

                <button type="submit" id="createBtn" class="btn btn-primary">Save</button>

                <div class="result"></div>
           
            </div>

               </form>
          </div>
        </div> 
      </div>




 <script
  src="https://code.jquery.com/jquery-3.6.0.js"
  integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
  crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>



<script type="text/javascript">

     $(document).ready(function()


        $('#formcast').on('submit', function(e)
            e.preventDefault();

            $.ajax(
                type: "POST",
                url:"castings",
                data : $('#formcast').serialize(),
                success: function(response)
                    console.log(response)
                    $('#castingmodel').modal('hide')
                    alert("Data saved");
                ,
                error: function(error)
                    console.log(error)
                    alert("Data not saved");
                
            );
        );
     );
 
</script>
</x-app-layout>

它没有显示任何错误并且数据没有插入到数据库中。

我检查了文件.env数据库的参数是否正确。

不知道是不是因为我在表单中上传的输入文件

【问题讨论】:

它会影响你的功能吗? 通过在函数中返回一些东西来检查它并在你的响应中控制它 也在函数中返回您的请求并确保它有您的照片 我检查了,它在函数中返回响应 里面有你的照片吗?我认为您没有通过 ajax 请求发送您的照片,因此根据您函数中的代码,您的数据将不会被保存 【参考方案1】:

您可以使用表单数据而不是序列化来提交您的表单,如下所示

$('#formcast').on('submit', function(e)
            e.preventDefault();
   var formData = new FormData(this);
            $.ajax(
                type: "POST",
                url: ' url('/agents') ',
                data: formData,
                success: function(response)
                    location.reload();
                ,
                error: function(error)
                   
                
            );

        );

由于在您的后端,您只有在上传图片时才会创建记录。所以请确保也上传文件

【讨论】:

【参考方案2】:

请检查这一行:

 $cast = new Casting; 

不应该

 $cast = new Casting();

带括号? 您还试图从表单中获取数据

($cast -> casting_name= $request->input('casting_name'); ) 

虽然您的 jQuery ajax 请求的内容类型不是 application/x-www-form-urlencoded 所以2个选项: 1- 像这样从控制器获取数据:

 $cast -> casting_name= $request->get('casting_name');

(用'get'代替'input'

2- 保留控制器并更新 ajax 内容类型

【讨论】:

以上是关于未使用 laravel 8 将数据插入数据库的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 8 和 Ajax - 将数据插入表中总是刷新加载

Laravel 数据库插入,查询操作

Laravel 8 无法在某个表中插入或更新数据

laravel 8:插入方法在 eloquent 中获取最后一个插入 id(插入方法)

Laravel Ajax 验证工作 [422 状态],但如果验证成功并且数据已插入数据库,则页面未重定向

Laravel 对多个插入的验证