您好我正在使用ajax进行CRUD,我的商店评论存在问题。 我有这个错误:
Connection.php第655行中的QueryException:SQLSTATE [23000]:完整性 约束违规:1048列' user_id'不能为null(SQL: 插入
comments
(content
,user_id
,product_id
,article_id
,updated_at
,created_at
)值(我的评论,,,, 2016-06-20 10:37:57,2016-06-20 10:37:57))
我试着用文字"我的评论"来存储评论。我的输入"内容"传递到我的控制器,但我的输入隐藏如" article_id"," user_id"," product_id"没有传递给我的控制器。
CommentController:
public function store(Request $request)
{
if($request->ajax()){
$comment = new Comment();
$comment->content = $request->input('content');
$comment->user_id = $request->input('user_id');
$comment->product_id = $request->input('product_id');
$comment->article_id = $request->input('article_id');
$comment->save();
return response()->json([
"message" => "Comment pubblished!"
]);
}
}
表单评论文章:
{!! Form::open(['route'=>'comment.store'] )!!}
<div class="form-group">
<label for="reply-text" class="sr-only">Commenta</label>
{!! Form::textarea('content', null, ['id'=>'content','class'=>'form-control','rows'=>'3', 'placeholder'=>'Commenta','required'])!!}
</div>
<input type="hidden" id="token" name="_token" value="{{ csrf_token() }}">
{!! Form::hidden('user_id', Auth::user()->id, null,['id'=>'user_id','class' =>'form-control'])!!}
{!! Form::hidden('article_id', $article->id, null,['id'=>'article_id','class' =>'form-control'])!!}
{!! Form::hidden('article_slug', $article->slug, null,['id'=>'article_slug','class' =>'form-control'])!!}
{!!link_to('#', $title='Comment post', $attributes =['id'=>'commento', 'class'=>'btn btn-lg btn-dark btn-outline'], $secure = null)!!}
{!! Form::close()!!}
comment.js:
$("#commento").click(function(){
var dato= $("#content").val();
var dato2= $("#user_id").val();
var dato3= $("#article_id").val();
var dato4= $("#product_id").val();
var route = "http://localhost:8000/comment";
var token = $("#token").val();
$.ajax({
url: route,
headers:{'X-CSRF-TOKEN':token},
type: 'POST',
dataType: 'json',
data:{
content: dato,
user_id: dato2,
article_id: dato3,
product_id: dato4
},
});
});
答案 0 :(得分:0)
将隐藏字段更改为:
{!! Form :: hidden(&#39; user_id&#39;,Auth :: user() - &gt; id,[&#39; id&#39; =&gt;&#39; user_id&#39;,&#39; class&#39; =&gt;&#39; form-control&#39;])!!}
{!! Form :: hidden(&#39; article_id&#39;,$ article-&gt; id,[&#39; id&#39; =&gt;&#39; article_id&#39;,&#39; class&#39; =&GT;&#39;形状控制&#39;])!}
{!! Form :: hidden(&#39; article_slug&#39;,$ article-&gt; slug,[&#39; id&#39; =&gt;&#39; article_slug&#39;,&#39; class&#39; =&GT;&#39;形状控制&#39;])!}