Google reCaptcha always resetting with laravel 5.1 - validation

I've searched about it on internet but it seems to be different. I'm using laravel5.1 and implemented google recaptcha. The scenario is, if the form was submitted and returns the validation with error, the recaptcha is resetting again and again, what I want is to not to reset it again, just staying as validated, because it annoys users to validate again and again. Do you have any idea about this?
Update: for code
public function postRegister(Request $request){
// Validation
$this->validate($request, [
'username' => 'required|unique:users|max:20|min:3',
'password' => 'required|min:6',
'retype_password' => 'required|same:password',
'email' => 'required|unique:users|email|max:255',
'g-recaptcha-response' => 'required|recaptcha'
]);
// Database save part here...
return redirect()->route('register')->with('info', 'Success!');
}

This is a little more verbose now that I am trying to write the code, but you get the gist.
Validate your Recaptcha field first. If it is valid, set a session variable to prevent it being rendered in your form again.
public function postRegister(Request $request)
{
// Prepare validation rules
$defaultRules = [
'username' => 'required|unique:users|max:20|min:3',
'password' => 'required|min:6',
'retype_password' => 'required|same:password',
'email' => 'required|unique:users|email|max:255',
];
$recaptchaRules = [
'g-recaptcha-response' => 'required|recaptcha',
];
// Set session if recaptcha is valid
if (Validator::make($request->all(), $recaptchaRules)->passes()) {
session(['recaptcha' => true]);
}
// Add recaptcha rules to default rules if failed to get single message bag with all errors
else {
$defaultRules = array_merge($defaultRules, $recaptchaRules);
}
// Validation
$this->validate($request, $defaultRules);
// Database save part here...
// Reset recaptcha validity so that the recaptcha is displayed on the next submission
session(['recaptcha' => false]);
return redirect()->route('register')->with('info', 'Success!');
}
Only output the Recaptcha field it if hasn't already been validated.
#unless (session('recaptcha'))
{{ Recaptcha::render() }}
#endunless

Related

How to validate inputs from GET request in Laravel

I wanted to validate inputs from a GET request without using the
this->validate($request... or \Validator::make($request...
and prefer to do it like
$input = $request->validate([... rules ...]);
however since get requests doesn't have $request parameters how can I achieve it?
public function sampleGet($param1, $param2) {
// How can I pass the $param1 and $param to to validate?
$input = $request->validate([
'param1' => 'required',
'param2' => 'required
]);
}
You can do so and it will have same behavior as validate
validator($request->route()->parameters(), [
'param1' => 'required',
'param2' => 'required'
....
])->validate();
If you want all the route parameters you can get them as an array:
$request->route()->parameters()
Since you already have those parameters being passed to your method you can just build an array with them:
compact('param1', 'param2');
// or
['param1' => $param1, 'param2' => $param2];
You are not going to be using the validate method on the Request though, you will have to manually create a validator. Unless you want to merge this array into the request or create a new request with these as inputs.
There is nothing special about the validate method on a Controller or on a Request. They are all making a validator and validating the data the same way you would yourself.
When manually creating a validator you still have a validate method that will throw an exception, which would be the equivalent to what is happening on Request and the Controller with their validate methods.
Laravel 7.x Docs - Validation - Manualy Creating Validators - Automatic Redirection
You can do like that.
public function getData(Request $request)
{
try {
$input['route1'] = $request->route('route1');
$input['route2'] = $request->route('route2');
$valid = Validator::make($input, [
'route1' => 'required',
'route2' => 'required'
]);
} catch (\Throwable $th) {
echo "<pre>";print_r($th->__toString());die;
}
}
Or you can follow the below link for more info.
https://laravel.com/docs/7.x/validation#manually-creating-validators

Laravel 5.5 Form Validation Request unique Rule no Data

Currently updating Laravel from v5.2 to 5.5 and can't figure out how I get the "unique" rule working on update.
This is my rule that works nice on Laravel 5.2
public function rules()
{
$retVal = [
'username' => 'required|alpha_dash|min:4|max:30',
'password' => 'min:6|confirmed',
'password_confirmation' => 'min:6',
'email' => 'required|email|unique:users,email,' . $user->id,
'roles_list' => 'required',
];
if (stristr($this->get('username'), '#'))
{
$retVal['username'] = 'required|email';
}
return $retVal;
}
But now in Laravel 5.5 I get always an "email unique"-error on update. When I type in the user-id manually it works. Like described in the Laravel docs it should work:
https://laravel.com/docs/5.5/validation#form-request-validation
I have no clue how to get the $user object accessible in my form request.
Thank you very much in advance for assist !
Your $user variables seems null.
If you're trying to retrieve the currently authenticated user in your Request class, you can try this:
$user = $this->user();
Next, you have to change your email rules a bit:
'email' => 'required|email|unique:users,email,' . ($user ? $user->id : 0),

Validate POST request Laravel?

I validate POST request like:
$validator = Validator::make($request->all(), [
"id.*" => 'required|integer'
]);
if ($validator->fails()) {
return response()->json($validator->errors, 400);
}
echo "Ok";
When I send request without parameter id it skips validation and returns echo "Ok";.
Why validation does not work?
If you expect id is array of integers you should update validation rules like this:
$validator = Validator::make($request->all(), [
"id" => 'required|array',
"id.*" => 'integer'
]);
First know when using $request->validate(); when it fail exceptions are raised!
And they are automatically handled by laravel. If it's a get, or a normal post form, then the process will redirect back to the form.
To note, 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.
If you want to not have such an automatic behavior, create manually a validator, then you can check with ->fails() method, as the example show bellow. That's can be handful in a lot of situations.
<?php
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
}
And there is no better then the doc itself: https://laravel.com/docs/5.7/validation
there is a lot of options, to personalize our validation process.

How to get paymentMethodNonce in Braintree API?

I'm working in laravel 5.4
My transactions are successfull when I try a 'fake_nonce' type of string provided by the braintree docs. But when I tried to get the paymentMethodNonce it always gives me error like nonce not found. And sometimes http error!!! If I try to configure it by myself!
Take a look at my controller function below
public function addOrder(Request $request){
$customer = Braintree_Customer::create([
'firstName' => $request->guest_name,
'email' => $request->guest_email,
'phone' => $request->guest_phone
]);
$customer->success;
$customer->customer->id;
$find = Braintree_Customer::find($customer->customer->id);
$nonceFromTheClient = Braintree_PaymentMethodNonce::find($find);
$result = Braintree_Transaction::sale([
'amount' => $request->subtotal,
'paymentMethodNonce' => $nonceFromTheClient,
'options' => [
'submitForSettlement' => True
]
]);
if ($result->success) {
$settledTransaction = $result->transaction;
} else {
print_r($result->errors);
}
Cart::destroy();
return view('guest/track', compact('result'));
}
$nonceFromTheClient = Braintree_PaymentMethodNonce::find($find);
Your using the wrong nonce, this nonce must come from the DropIn ui and not be generated on your code.
Please check the onPaymentMethodReceived() method provided in the JS SDK.
Please check this reference

How to set remember_token NULL in laravel

I have an application in laravel which have a Users table with a column remember_tokenand the User model has the three function mentioned here: http://laravel.com/docs/upgrade#upgrade-4.1.26
getRememberToken(), setRememberToken($value), getRememberTokenName()
In my login form, I have email, password and a remember me checkbox field. What I want is if user ticked that Remember Me checkbox, then only laravel should remember the user, else it should set the column as NULL.
But at the moment it is remembering it all the time, and I don't know how to set it to NULL.
My doLogin function code is below:
public function doLogin()
{
$rules = array(
'email' => 'required|email',
'password' => 'required|alphaNum|min:7'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect::to('login')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
$remember = Input::get('remember');
$userData = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
// attempt to do the login
if (Auth::attempt($userData, true)) {
return Redirect::to('/');
} else {
return Redirect::to('login')->with('loginError', 'Incorrect email or password.');
}
}
}
Please tell me what modification I need to make so that it set remember_token as null in database when remember checkbox is not ticked by user.
To quote the documentation
If you would like to provide "remember me" functionality in your
application, you may pass true as the second argument to the attempt
method, which will keep the user authenticated indefinitely (or until
they manually logout).
You are hard coding the second parameter to true instead of using the value taken from the user input.
You are already setting the input to the $remember variable, so try passing that instead.
Auth::attempt($userData, $remember)

Resources