Inject an error message to errors object - laravel-4

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']));

Related

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

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

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.

Data validation in Laravel is not working

I've created a custom request in my project, but somehow it is not working. I'm facing two errors. I'm trying to show a message on view if validation fails through Ajax.
1) 422 Unprocessable Entity error
and
2) Undefined variable: teacherrequest
validation rules which i set in Request folder,
TeacherRequest.php:
public function rules()
{
return [
'Name' => 'required|regex:/^[\pL\s\-]+$/u',
'FName' => 'required|regex:/^[\pL\s\-]+$/u',
];
}
Controller:
public function update(TeacherRequest $request, $id)
{
if ($teacherrequest->fails()) {
return response()->json([
'msg' => 'Please Enter Correct Data',
]);
}
}
AJAX:
success: function (data) {
if(data.msg){
alert("please validate data");
}
}
Update:
if i remove if condition, i am getting 422 error, how to show that on view?
First, public function update(TeacherRequest $request) so in the function you need to use $request not $teacherrequest.
And second You need to have public function authorize() returning true.
You define TeacherRequest as $request TeacherRequest $request
but in next line use it as
if ($teacherrequest->fails()){ // this is wrong
correct one should be define like this
TeacherRequest $teacherrequest
or if you didn't change the dependency injection, just change the validator like this
if ($request->fails()){
summary: why error happened already specifically explained which is undefined teacherrequest variable, therefore 2 solutions above can solve it
If you type hint your request class as a parameter in your controller's action method (like you are doing in the example above) Laravel will automatically run your validation rules and return a 422 Unprocessable Entity if validation fails. You don't need to manually check if validation fails like you're doing above; in your controller's update method you can just implement the logic you want to run when validation passes.
Also on your front end you will need to use the error ajax callback to display the error message because a 422 status code is not considered successful.
See the documentation on creating form requests.
So, how are the validation rules evaluated? All you need to do is type-hint the request on your controller method. The incoming form request is validated before the controller method is called, meaning you do not need to clutter your controller with any validation logic.

Array number/position in custom Laravel validation messages

When validating arrays in Laravel and using custom error messages, is there any way to access the array number/position that is throwing the validation failure?
Trying to manipulate :attribute or :key in the messages array of the Request doesn't work as the placeholders are later translated (read: they aren't the actual variables)
I am trying to present a message like:
object.property.*.required => 'The property on object # is required'
Otherwise you end up with something like:
object.property.3 is required
I'd like to grab the number so I can present a friendlier and more descriptive message.
Well, this can be achieved by the replacer method on the Validator facade. Add the replacer in AppServiceProvider#boot method.
//...
public function boot()
{
Validator::replacer('required', function ($message, $attribute, $rule, $parameters) {
if (str_contains($message, ':nth') && preg_match("/\.(\d+)\./", $attribute, $match)) {
return str_replace(":nth", $match[1]+ 1, $message);
}
return $message;
});
}
//...
The custom validation message for the attribute must contain the palceholder :nth
object.property.*.required => 'The property on object :nth is required'

Resources