我刚刚开始使用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
{
//
}
输出(空白字段)
答案 0 :(得分: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
然后在你的controller store()方法中:
$product = new Product();
$product->fill($request->all())->save();
答案 1 :(得分:1)
也许Laravel专家会出现并发现错误。在此之前,尝试通过跟踪从前端传递到数据库的数据来定位它。 所有数据是否实际由浏览器发送并由服务器接收?
发布数据时是否会触发?
if(data.notify == "Success"){
console.log(data.notify);
}
发布数据时保持调试器的网络选项卡处于打开状态,并确保全部发送。
尝试通过更改以下行来返回/回显整个帖子数据:
return json_encode(array('notify'=>$notification));
在黑暗中拍摄:如果你在javascript的末尾删除了“json”,会发生什么?
答案 2 :(得分:0)
你应该在盲目尝试之前学习。也许,标准请求首先是ajax然后因为csrf令牌存在一些问题。
您需要设置可填写字段:
class Product extends Model
{
protected $fillable = ['unit', 'price', etc...;
我推荐你这个系列:laracasts.com