【问题标题】:Blank data is inserted in PostgreSQL using Laravel使用 Laravel 在 PostgreSQL 中插入空白数据
【发布时间】:2016-03-05 11:21:15
【问题描述】:

我刚开始使用 laravel,但我在这部分上有所保留,其中我无法使用 PostgreSQl 成功地将用户输入的数据保存在数据库中,因为它只显示除 id 及其时间戳之外的空白条目。为什么使用 Laravel 在我的数据库字段中插入空白数据?这是我的代码:

Javascript

<script type="text/javascript">

 $(".submit-prod").click(function(e){

 e.preventDefault();

   $.post("{{ url('/addprod') }}",$("#prod-form").serialize(),function(data) {

       if(data.notify == "Success"){
         console.log(data.notify);
       }

    },"json");

}); //end

Route.php

Route::group(['middleware' => 'web'], function () {

Route::auth();

Route::get('/', function () {
    return view('welcome');
});

Route::any('addprod', 'Product\ProductController@store');

Route::get('/home', 'HomeController@index');
});

ProductController.php

<?php

namespace App\Http\Controllers\Product;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Product\Product as Product;

class ProductController extends Controller
{

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    return view('home');
}

public function store(Request $request){

    $products = Product::create($request->all());


      if($products){

        $notification = "Success";

      } else{
        $notification = "Failed";
      }

      return json_encode(array('notify'=>$notification));

    }
  }

模型(Product.php)

<?php

 namespace App\Product;

 use Illuminate\Database\Eloquent\Model;

 class Product extends Model
 {
  //
 }

输出(空白字段)

【问题讨论】:

  • 请帮帮我。请提供任何帮助。

标签: php ajax postgresql laravel laravel-5.2


【解决方案1】:

您需要为要填充模型的列启用批量分配。 例如:

 namespace App\Product;

 use Illuminate\Database\Eloquent\Model;

 class Product extends Model
 {
  protected $fillable = ['quantity'];
 }

https://laravel.com/docs/5.1/eloquent#mass-assignment

然后在你的控制器 store() 方法中:

$product = new Product();
$product->fill($request->all())->save();

【讨论】:

  • 已经完成了,但仍然空白:(请帮助我。我几乎正在寻找一天的时间来回答这个问题,但一点运气都没有。
【解决方案2】:

也许 Laravel 专家会出现并发现错误。在此之前,请尝试通过跟踪从前端到后端再到数据库的数据来定位它。 所有的数据实际上是由浏览器发送并由服务器接收的吗?

当你发布数据时会触发吗?

   if(data.notify == "Success"){
     console.log(data.notify);
   }

在您发布数据时保持调试器的网络选项卡处于打开状态,并确保所有数据都已发送完毕。

尝试通过更改此行将整个帖子数据返回/回显到浏览器:

return json_encode(array('notify'=>$notification));

黑暗中的一枪:如果删除 javascript 末尾的“json”会发生什么?

【讨论】:

    【解决方案3】:

    你应该先学习再盲目尝试。也许,标准请求首先是 ajax,因为 csrf 令牌存在一些问题。

    您需要设置可填写的字段:

    class Product extends Model
    {
        protected $fillable = ['unit', 'price', etc...;
    

    我推荐你这个系列:laracasts.com

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-11
      • 1970-01-01
      • 2013-09-19
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      相关资源
      最近更新 更多