my store method
the FormRequest
the validation is working and I get the confirm message in controller but when the validation fails I get no error messages any advice?
You can use validation in controller like this, hopefully it will work for you
$validator = Validator::make($request->all(), [
'id' => 'required|string|regex:/(^([A-Z]){2,4}_([0-1]){1}_([0-1]){1}_([0-9]){10})/u'
]);
if ($validator->fails()){
return (Arr::first(Arr::flatten($validator->messages()->get('*')));
}
else{
//your code
}
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json([
'errors' => $validator->errors(),], 403));
}
this worked for me, just needed to return the errors in json format
Related
I have a form that using ajax for update data client. In that form there is an input file. Everything is going fine except for updating the file. File is sent, it changed on storage too, but it gives error on validation and didn't change data on database.
Here is the code on the controller :
public function update(Request $request, Client $client)
{
$validatedData = Validator::make($request->all(), [
'name' => 'required|max:255',
'logo'=> 'image|file|max:100',
'level' => 'required|max:1'
]);
$validatedData['user_id'] = auth()->user()->id;
if ($validatedData->fails()){
return response()->json($validatedData->errors());
} else {
if($request->file('logo')){
if($request->oldLogo){
Storage::delete($request->oldLogo);
}
$validatedData['logo'] = $request->file('logo')->store('logo-clients');
}
$validateFix = $validatedData->validate();
Client::where('id', $client->id)->update($validateFix);
return response()->json([
'success' => 'Success!'
]);
}
}
It gives error on line :
$validatedData['logo'] = $request->file('logo')->store('logo-clients');
With message :
"Cannot use object of type Illuminate\Validation\Validator as array"
I use the same code that works on another case, the difference is the other not using ajax or I didn't use Validator::make on file input. I guess it's just wrong syntax but I don't really know where and what it is.
To retrieve the validated input of a Validator, use the validated() function like so:
$validated = $validator->validated();
Docs:
https://laravel.com/docs/9.x/validation#manually-creating-validators
https://laravel.com/api/9.x/Illuminate/Contracts/Validation/Validator.html
$validatedData is an object of type Illuminate\Validation\Validator.
I would say the error is earlier there as well as this line should give an error also:
$validatedData['user_id'] = auth()->user()->id;
As ericmp said, you first need to retrieve the validateddata to an array and then work with it.
I'm trying to use the Laravel validator to include some custom error messages before I run the validate() method. However it appears that running this method then removed any previously added errors.
I can confirm that the error message appears when I dump out the validator messages before hitting validate()
$validator = Validator::make(
$this->data,
$this->rules
);
$validator->errors()->add('meal', 'The meal field is required.');
$validator->validate();
How I can validate my data but still include the error relating to the meal?
I believe what you want to use is the after validation hook. This will allow you to add more errors like so:
$validator = Validator::make(
$this->data,
$this->rules
);
$validator->after(function ($validator) {
$validator->errors()->add(
'field', 'Something is wrong with this field!'
);
});
$validator->validate();
I am trying to implement multiple column as unique(title,created_by). A user can not create duplicate title.
The validation give me error both in separate request class also.
The validation code is:
$created_by = auth()->user()->id;
$this->validate($request, [
'title' => 'required|max:50|unique:register_types,title,null,id,created_by,'.$created_by
]);
The code give error as "Method Illuminate\Http\Request::first does not exist"
But Validator method works successfully.
The code is:
$validator = \Validator::make($request->all(),[
'title' => 'required|max:50|unique:register_types,title,null,id,created_by,'.$created_by
]);
if ($validator->fails()) {
return $validator->errors();
}
I want to use first clean code pattern. How is it possible ?
I got my problem.
Some days ago, I have added a condition at render method in handler class:
elseif ($exception instanceof ValidationException) {
return $exception->first();
}
Solution:
At this time, just I blocked this condition.
Problem solved.
I have this route in route/api.php:
Route::post('/register', 'LoginController#register');
My LoginController
class LoginController extends Controller {
public function register(Request $request) {
$this->validate($request, // <-- using this will return the view
// from **web.php** instead of the expected json response.
[
'email' => 'required|email',
'firstName' => 'required|alpha_dash',
'lastName' => 'required',
'password' => 'required|confirmed',
]);
$input = $request->all();
//$plain_password = $input['password'];
$input['uuid'] = uuid();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
dd($errors);
$response['succes'] = true;
$response['user'] = $user;
return response($response);
}
}
Why does adding a validation call change the behaviour to returning my view / the wrong route. I want the api to validate my request too, not just my "frontend".
When you use Laravel's validate method from controller it automatically handles/takes the step if the validation fails. So, depending on the required content type/request type, it determines whether to redirect back or to a given url or sending a json response. Ultimately, something like thos following happens when your validation fails:
protected function buildFailedValidationResponse(Request $request, array $errors)
{
if ($request->expectsJson()) {
return new JsonResponse($errors, 422);
}
return redirect()->to($this->getRedirectUrl())
->withInput($request->input())
->withErrors($errors, $this->errorBag());
}
So, if the first if statement is true then you'll get a json response and it'll be true if you either send an ajax request or if you attach a accept header with your request to accept json response (When requesting from a remote server). So, make sure your request fulfills the requirements.
Alternatively, you can manually validate the request using the Validator component and return a json response explicitly if it fails.
I have very big problem.
When I submit my form with data everything goes well, but when I won't fill one field in my form laravel throw error MethodNotAllowedHttpException in RouteCollection.php line 218
I have validation in my controller but it does not change anything. When the form is empty it throws an error.
Somebody has a solution for this error?
In your route for this form post use veriables as optional. Use ? In your route definition.
/{var?}/{var2?}/......
From laravel docs-
Occasionally you may need to specify a route parameter, but make the presence of that route parameter optional. You may do so by placing a ? mark after the parameter name. Make sure to give the route's corresponding variable a default value:
Route::get('user/{name?}', function ($name = null) {
return $name;
});
Route::get('user/{name?}', function ($name = 'John') {
return $name;
});
or
// validate the info, create rules for the inputs
$rules = array('data_rozpoczecia' => 'required', 'data_zakonczenia' => 'required');
// run the validation rules on the inputs from the form
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) { return redirect()->back(); } else{ //do what you want. }