How to Set Session in Form Request Validation Laravel? - laravel

I create validation using laravel form request file and I want to set session in laravel request file and send the session with validation error to blade view.. can I do that ?
Thanks :)

Using Laravels validation whether that be within the App\Http\Requests or in the controller itself using
$this->validate($request, [
'name' => 'required
]);
Will automatically return errors back to the view itself for you to display within the $errors variable.
If you're calling the Validator::make() method yourself and wish to check the errors manually and redirect. You can do this by using
$validator = Validator::make($request, [...]);
if($validator->fails()) {
return redirect()->back()->withErrors($validator->errors());
}

Related

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.

How do I make all validate() calls to execute in a controller?

In a controller I am using two validation like this:
public function update(Request $request){
if( $request->hasFile('img1') ){
$request->validate(
[
'img1'=>'image'
]
);
}
if( $request->hasFile('img2') ){
$request->validate(
[
'img2'=>'image'
]
);
}
}
Now if I upload incorrect file types for both img1 & img2 Only the first validation is checked and laravel redirects user to the original form page. This way message for only first validation is displayed. Even though second file type was also incorrect. I want to make sure all validate methods are checked are executed before I get redirected to the page I came from i.e., the page containing form.
Also I can't put validate method for file in one if statement as img1 and img2 might not be present at the same time. Because user might just want to upload one file.
You need not invoke validate method more than once for validating a single request. In the validate method you can validate all the inputs from the request, and if the validation fails, then it will automatically return the page which the request came from. And also you need not check whether the request has the input or not, before the validation. It will automatically be managed by laravel.
In the following validation required is used to specify the field is mandatory, and it will only accept file types specified in mimes, and max is used to specify the maximum file size in kilobytes.
public function update(Request $request){
$request->validate([
'img1' => 'required | mimes:jpeg,jpg,png | max:1000',
'img2' => 'required | mimes:jpeg,jpg,png | max:1000',
]);
}
you can try
public function update(Request $request){
$request->validate([
'img1' => 'required_without:img2',
'img2' => 'required_without:img1'
]);
}
If have more than two fields and only one is required, use required_without_all:foo,bar,...

Laravel 5.5 - Include Find function inside Validation Rule

I am using validation in an Laravel 5.5 controller like this...
$membership = Membership::find($request->input('membership_id'));
/* Validation Rules */
$rules = [
'key' => [
'required',
Rule::in([$membership->key]),
],
];
This works correctly if membership_id is provided, but if not then it with error....
Trying to get property of non-object
Is there a way I can include the Membership:find function inside of the validation Rule instead so that is respects the require validation?
Use the optional() helper to avoid the "Trying to get property of non-object" error:
Rule::in([optional($membership)->key]),
So, if membership will not be found, null will be returned and a user will be redirected back with validation error message.

How to validate params in REST Lumen/Laravel request?

Route:
$app->get('/ip/{ip}', GeoIpController::class . '#show');
How to validate ip's properly? I've tried to inject Request object in show method, but wasn't able to solve this. I want to stick with REST, so using URL parameters is not solution for me. I use it for API purposes, so status code as response would be appropriate.
Also tried that way:
$app->bind('ip', function ($ip) {
$this->validate($ip, [
'ip' => 'required|ip',
]);
});
EDIT:
The answer below is correct, I've found more info about requests in documentation:
Form requests are not supported by Lumen. If you would like to use form requests, you should use the full Laravel framework.
In other words, you cannot use custom requests via injection in constructors in Lumen.
The validate method takes the request object as the first parameter. Since you're passing the ip in the route, you need to create a custom validator.
public function show($ip)
{
$data = ['ip' => $ip];
$validator = \Validator::make($data, [
'ip' => 'required|ip'
]);
if ($validator->fails()) {
return $validator->errors();
}
return response()->json(['All good!']);
}
Edit : This is all laravel does under the hood. You could basically you this function directly to validate the ip and save a lot of effort.
protected function validateIp($ip)
{
return filter_var($ip, FILTER_VALIDATE_IP) !== false;
}

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

Resources