I am trying to store comments and display the result on the same page with an Ajax call. But I keep getting this error in my console
422 (Unprocessable Entity)
Let's start with my Comment model:
class Comment extends Model
{
// fields can be filled
protected $fillable = ['body', 'user_id', 'image_request_id'];
/**
* Get the user that owns the Comment.
*/
public function user()
{
return $this->belongsTo('App\User');
}
}
Let's continue with my form:
{!! Form::textarea('body', null, ['class'=>'form-control', 'rows' => 3]) !!}
{!! Form::hidden('image_request_id', $imageRequest->id) !!}
Let's see out controller method: (CommentController.php)
public function store(CommentRequest $request)
{
$comment = Auth::user()->comments()->save(new Comment($request->all()));
$response = array(
'status' => 'success',
'comment' => $comment
);
return response()->json($response);
}
My rules method in me CommentRequest.php
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'body' => 'required|max:1000',
];
}
Let's see our ajax.js
$( document ).ready(function() {
$('#storeComment').on('submit', function(e) {
e.preventDefault();
$('#storeComment').on('submit', function(e) {
e.preventDefault();
// Retrieve form data
var formData = [];
var data = $(this).serializeArray();
$.each(data, function(index, field) {
formData[field.name] = field.value;
});
// Post request with temp as data
axios.post('/comments', temp).then(function(data) {
console.log(data);
});
});
});
});
When I don't use ajax everything workes and the data is being stored.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire