Laravel Validator. Unable to retrieve both errors and Input - php

I am using Laravel for a project and i am trying to validate some input fields from a form. I am using the Validator class.
Here is the code in my controller.
$validator = Validator::make($request->all(), [
'arithmos_kinhths' => 'required',
'kathgoria_kinhths' => ['required',Rule::notIn(['-'])],
'prohgoumenos_paroxos_kinhths' => ['required',Rule::notIn(['-'])],
'programma_kinhths' => ['required',Rule::notIn(['-'])],
'project_kinhths' => ['required',Rule::notIn(['-'])],
'kathogoria_epidothshs_kinhths' =>['required',Rule::notIn(['-'])],
'talk_to_eu_kinhths' => ['required',Rule::notIn(['-'])],
'pagio_kinhths' => 'required',
'sms_kinhths' => ['required',Rule::notIn(['-'])],
'internet_kinhths' => ['required',Rule::notIn(['-'])],
'international_kinhths' => ['required',Rule::notIn(['-'])],
'twin_sim_kinhths' => ['required',Rule::notIn(['-'])],
'wind_unlimited_kinhths' => ['required',Rule::notIn(['-'])],
]);
if ($validator->fails()) {
return back()->withErrors($validator)->withInput();
}
In the blade file i am trying to catch the errors using the code bellow.
#if($errors->any())
#foreach($errors->all() as $error)
<script>
$.notify(
{
title: '<strong>ERROR!</strong>',
message: '{{$error}}',
},
{
type: 'danger',
},
)
</script>
#endforeach
#endif
Also i want to put the old values into the input fields using {{old('value'}}
The problem i have is that i can't combine both errors and inputs. If i return only the errors using withErrors($validator) the errors are printed out. And if i return only withInput i have the post values.
Any ideas?

withInputs()
try this, i hope that help a little , or
you can
return back()->with('errors',$validator)->withInputs()

you can use $this->validatorWith([]) then follow your code, you don't need to manually redirect back to that page. your request will auto redirect to that page from where request has happened. this function belongs to trait Illuminate/Foundation/Validation/ValidatesRequests which is use by app\Http\Controllers\Controller.php. you just need to use. for more about this trait see here ValidateRequest
$this->validatorWith([
'request_param' => 'required',
]);

Related

Laravel old POST data empty after validation

I am printing the contents of old() in my view:
{{ print_r(old('steps'), true) }}
When I submit the form with the following validation rules, the old data prints fine:
$this->validate($request, [
'steps.*.name' => 'required',
]);
When I add more rules, the old data dissapears completely:
$this->validate($request, [
'steps.*.name' => 'required',
'steps.*.title' => 'required',
'steps.*.type' => 'required',
'steps.*.answer_options' => 'nullable|required_if:steps.*.type,Question',
'steps.*.input_type' => 'nullable|required_if:steps.*.type,Input',
]);
I've confirmed this only happens AFTER validation. How do I fix this?
Try to set SESSION_DRIVER=file to get it work
See related

Handle validator to return json

Laravel throw an exception at $validator->fails() call.
Ok, I just want to create a stateless register method in ApiController.php with Laravel 5.7.
I used the Validator facade to check the sent data.
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()],
Response::HTTP_UNAUTHORIZED);
}
But, when I use xdebug, I see something strange. The fails methods seems throw an exception.
Laravel send an error HTML page with title:
Validation rule unique requires at least 1 parameters.
The route is used in api.php
Route::post('register', 'Api\UserController#register');
Do you have an explanation for this?
Thx for reading.
The syntax for unique rule is unique:table,column,except,idColumn.
So i changed it for you to use the users table.
If you don't want to use the users table change the users part behind unique:
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required',
'c_password' => 'required|same:password',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()],
Response::HTTP_UNAUTHORIZED);
}
For more information on the unique rule see this: https://laravel.com/docs/5.7/validation#rule-unique
In your API request add the following header:
...
Accept: application/json // <-----
This will tell Laravel that you want a response in a json format.
Note: this is different to the Content-type: application/json. The later indicates the format of the data tha is being sent in the body.

How to get validation message in laravel 5.5

hi folks I'm working on Laravel 5.5 and here I need to display validation messages for my API upto now I have done like this
$validator = Validator::make($request->all(),[
'first_name' => 'email|required',
'last_name' => 'nullable',
'email' => 'email|required',
'mobile_no' => 'nullable|regex:/^[0-9]+$/',
'password' => 'required',
]);
if($validator->fails)
{
$this->setMeta('status', AppConstant::STATUS_FAIL);
$this->setMeta('message', $validator->messages()->first());
return response()->json($this->setResponse(), AppConstant::UNPROCESSABLE_REQUEST);
}
Since Laravel 5.5 has some awesome validation features I am looking to validate my request like this
request()->validate([
'first_name' => 'email|required',
'last_name' => 'nullable',
'email' => 'email|required',
'mobile_no' => 'nullable|regex:/^[0-9]+$/',
'password' => 'required',
]);
But I am facing issue here what should I do to check if the validation fails? Like I was doing by if($validator->fails)
In Laravel 5.5, like the documentation mention, the validation process is very easy :
Displaying The Validation Errors :
So, what if the incoming request parameters do not pass the given
validation rules? As mentioned previously, Laravel will automatically
redirect the user back to their previous location. In addition, all of
the validation errors will automatically be flashed to the session.
Again, notice that we did not have to explicitly bind the error
messages to the view in our GET route. This is because Laravel will
check for errors in the session data, and automatically bind them to
the view if they are available.
AJAX Requests & Validation :
In this example, we used a traditional form to send data to the
application. However, many applications use AJAX requests. When using
the validate method during an AJAX request, Laravel will not generate
a redirect response. Instead, Laravel generates a JSON response
containing all of the validation errors. This JSON response will be
sent with a 422 HTTP status code.
So as you said : that means you don't need to put your ifs to handle validation laravel will take care of them itself great :)
here is some syntax that i use
public static $user_rule = array(
'user_id' => 'required',
'token' => 'required',
);
public static function user($data)
{
try{
$rules = User::$user_rule;
$validation = validator::make($data,$rules);
if($validation->passes())
{
}
else
{
return Response::json(array('success' => 0, 'msg'=> $validation->getMessageBag()->first()),200);
}
return 1;
}
catch(\Illuminate\Databas\QueryException $e) {
return Response::json(array('success' => 0, 'msg' => $e->getMessage()),200);
}
}
hope this will help you!
Please add Accept: application/json in you header.
Laravel automatically send an error message with response code.
As per 2019 Laravel 5.8 it is as easy as this:
// create the validator and make a validation here...
if ($validator->fails()) {
$fieldsWithErrorMessagesArray = $validator->messages()->get('*');
}
You will get the array of arrays of the fields' names and error messages.
You can show first error.
if ($validator->fails()) {
$error = $validator->errors()->first();
}
For all error :
$validator->errors()

Add a validation which is not related to the form

I want to add a validation on a form. My actual form works, here it is:
public function store(Request $request, $id)
{
$this->validate($request, [
'subject' => 'required',
'body' => 'required',
]);
// Do something if everything is OK.
}
Now, I want to check if the user is "active" too. So something like:
\Auth::user()->isActive();
And return an error with the other validation errors if the user is not active.
Can I append something to the validator that has no relation with the form itself? I mean I want to add an error to the other errors if the user is not active.
That code is only validating the request variable (first argument of validate() function). So you will have to put someting in the request to validate it. It applies the rules to the object/array given.
$request->is_active = Auth::user()->isActive();
$this->validate($request, [
'subject' => 'required',
'body' => 'required',
'is_active' => true //or whatever rule you want
]);
Anyways, I never tried that so not sure it will work. The usual way is to do an if
if ( !Auth::user()->isActive() ) {
return redirect->back()->withErrors(['account' => 'Your account is not active, please activate it']);
}
//continue here

Laravel - mimes:pdf not working

I have a form with an input which allows to upload PDFs.
Here is the method that validates my input :
protected function validator(array $data)
{
return Validator::make($data, [
'title' => 'required|max:255|string',
'artist' => 'required',
'notes' => 'nullable|string',
'file' => 'required|mimes:pdf|max:500',
'g-recaptcha-response' => 'required|captcha',
]);
}
The rules are working for all the other fields, but it does not work for the file input. Whatever I upload, PDF or not, I have the following error :
The file must be a file of type: pdf.
I just solved my issue.
In case someone has the same problem, you need to set the enctype attribute of your form to multipart/form-data.
In short, something like this :
<form action="#" enctype="multipart/form-data">
...
</form>
The error is not very clear, so I hope this helps.

Categories