Answer the question
In order to leave comments, you need to log in
How to fix 422 Ajax and Laravel error?
Hello.
I get this error 422 (Unprocessable Entity), I googled it seems like the error is related to data validation, but I messed up somewhere.
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$( "#form" ).submit(function( e ) {
e.preventDefault();
var message = $('#message').val();
var img = $('#img').val();
var user_id = $('#user_id').val();
var _token = $('input[name="_token"]').val();
$.ajax({
type: "POST",
url: "{{route('profile.store', ['id' => Auth::user()->id])}}",
data: {message:message, img:img, user_id:user_id, _token:_token},
success: function (data) {
$("#textpost").html($(data).find("#textpost").html());
},
});
});
</script>
public function store(Request $request) {
$validator = $this->validate($request,[
'message' => 'required|max:1000',
'img' => 'mimes:jpeg,png,gif|max:3000',
]);
if($validator ) {
$post = new Profile();
$post->message = $request->message;
$post->user_id = Auth::user()->id;
if($request->file('img')) {
$path = Storage::putFile('public', $request->file('img'));
$url = Storage::url($path);
$post->img = $url;
}
$post->save();
}
return redirect()->back();
}
Answer the question
In order to leave comments, you need to log in
The data you submit is not validated:
[
'message' => 'required|max:1000',
'img' => 'mimes:jpeg,png,gif|max:3000',
]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question