menu

arrow_back Why doesn't the data go through validation in laravel?

by
1 vote
The situation is as follows. A json sent via fetch arrives.
Json is valid, everything is ok, but it doesn't pass the validation, although the controller is called and data is put in the database (there's a method in the code below). To make sure the controller is running, I returned the dd and it came back.
None of the following options work
Do not pay attention to the fact that the data for verification is different, I had to at least check somehow.

public function validator(Request $request)
{

$validator = Validator::make($request->all(), [
'first_name' => 'first_name|unique:users',
'last_name' => 'last_name|unique:users',
]);

$this->validate($request, [
'first_name' => 'required|unique:posts|max:255',
'last_name' => 'required', //required - обязательно для заполнения
'phone' => 'required|unique:user|min:11|max:11',
'document_number' => 'required|unique:user|min:10|max:10',
'password' => 'required|min:8',
]);
}
Did it this way: https://laravel.com/docs/5.0/validation#controller... There you go: https://laravel.com/docs/5.0/validation#form-reque... It was one of the first options:
$this->validate($request, [
'first_name' => 'required|unique:posts|max:255',
'last_name' => 'required',
'phone' => 'required|unique:user|min:11|max:11',
'document_number' => 'required|unique:user|min:10|max:10',
'password' => 'required|min:8',
]);
How do I validate the data? I need to return a json with an array of errors, in case the data didn't pass validation. Right now it is validated anyway

6 Comments

Sanes I'm not the eighth version, but I'm not the eighth version. But I don't have version 8 either. I have 5.8.
Is version 5.0 in the links confusing? You're doing something weird with request.
VicTHOR I did, and it didn't work. It still ignores the validation
To make sure the controller was running, I brought back dd and it came back.
to eat, I made a trek to the store and it made...

Do Request and take it in the controller instead of the normal one.
VicTHOR I did that, but it still doesn't pass the test. I only check the data in sql, which returns an error to me
Leo Mavrin , make a dump in the reQuest to make sure that the data passes through it.

2 Answers

by
0 votes
For all the Laravel martyrs)
Check how you send the request. Because my problem was that I didn't put
'Accept': 'application/json'

This is what the query should look like:
And in api, you don't have to write /api in root, in laravel, but in fetch you do!
fetch("/api/register", {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8',
'Accept': 'application/json'
},
body: json
}
by
0 votes
$request->validate()

It's better not to bother with all this, and use the package laravel-actions