Laravel Validate ->validate() method removed custom added errors? - laravel

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();

Related

Laravel form request messages not appearing when validation fails

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

Method Illuminate\Http\Request::first does not exist in laravel 6 error

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.

Laravel if one of the fields is not set, laravel throws error

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. }

non-static method basemodel::validate() should not be called statically,assuming $this from compatible context

Was tryin to validate my registration form calling the validation method from the basemodel in my controller
The method
public function postSIgnup ()
{
$validation = User::validate(Input::all());
}
Routes
Route::post('register', array('before=>'csrf', 'uses'=>'UsersController#postSignup'));
Help mi solve this problem
You can't just say 'validate my whole form'.
The reason this error occurs is because you are trying to use the validation method from Laravel.
Basic Form Validation in Laravel
First you want to grab all your form data/content.
$input = Input::all();
Secondly you can setup some rules. Those rules can be set in an array which Laravel will use.
Make sure the names are correctly spelled. (Those are the ones u used in your form-template.)
$rules = array(
'real_name' => 'Required|Min:3|Max:80|Alpha',
'email' => 'Required|Between:3,64|Email|Unique:users',
'age' => 'Integer|Min:18',
'password' =>'Required|AlphaNum|Between:4,8|Confirmed',
'password_confirmation'=>'Required|AlphaNum|Between:4,8'
);
To make use of the validator you have to create anew instance first:
You attach the form input and the rules you have set above.
When they match you can save your form to your database or what else you would like to do with it. That will probably look like:
$validator = Validator::make($input,$rules);
Cool,
We can check now if the Validator passes or not...
if($validator->fails()){
$messages = $validator->messages();
return Redirect::to('yourpage')->withErrors($messages);
}else{
// Handle your data...
}

Inject an error message to errors object

Is there a way to inject an error message so we can show it on a view with $errors instance, on a redirection?
$errors->all(); // e.g. to have it here
Which I tried:
return Redirect::to('dashboard')
->with('errors', 'Custom error');
But actually will throw an error:
Call to a member function all() on a non-object
Your example doesn't work since you're passing just a variable instead of an object.
If you want to add your own custom error message to other validation errors, you can use the add() method of Illuminate\Support\MessageBag class (since validation errors are returned as an instance of this class):
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
$errors = $validator->messages();
$errors->add('Error', 'Custom Error');
return Redirect::to('dashboard')->withErrors($errors);
}
Now your custom message should display alongside other validation errors.
Simple, one line solution
While what kajetrons said is completely true, it is unnecessary to create a validator if you just want to return an error message through the $errors object. This can be written more simply in one line:
return Redirect::to('dashboard')->withErrors(new \Illuminate\Support\MessageBag(['Custom error']));

Resources