Laravel 5.5 Form Validation Request unique Rule no Data - laravel

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),

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 unique validation rule with except not working

Laravel unique validation rule with except column not working on update, what's wrong in my code ?
public function update(Request $request, Article $article)
{
abort_if($article->user_id !== $request->user()->id, 403);
$article = $request->user()->articles()->update($request->validate([
'title' => [
'required',
Rule::unique('articles', 'title')->ignore($article->id)
],
'content'=>'required|min:90',
]));
return redirect('articles/'.$article->id)->withSuccess('Article saved.');
}
Error : The title has already been taken.
Laravel version : 6.4.0
Thanks for help
You can pass the entire instance of article to validate like:
Rule::unique('articles')->ignore($article);
Because you are already saying what column to check.
https://laravel.com/docs/6.x/validation
Remove title from
Rule::unique('articles', 'title')->ignore($article->id)
to
...
$article = $request->user()->articles()->update($request->validate([
'title' => [
'required',
Rule::unique('articles')->ignore($article->id)
],
'content'=>'required|min:90',
]));
...
Hope this helps
more info, check rule-unique
If you run the update on $request->user()->articles() you will update all of the user's articles. If the user only has 1 article then it should work just fine, however if there are more then this will result in data being overwritten.
Instead do:
$article->update($request->validate([
'title' => [
'required',
Rule::unique('articles', 'title')->ignore($article->id)
],
'content'=>'required|min:90',
]));

Laravel, Forcing A Unique Rule To Ignore A Given ID

I am following the instructions from the Laravel Documentation but I can't seem to make the rule work. Basically, I want to add a unique rule for both email and username fields for updating the user profile, but it doesn't seem to work. Am I missing something?
Here is the function for updating user credentials
public function updateCredentials(Request $request, User $user)
{
Validator::make($request->all(), [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'username' => [
'required','string','min:4','max:255',
Rule::unique('users')->ignore($user->id),
],
'email' => [
'required','string','email','max:255',
Rule::unique('users')->ignore($user->id),
],
'asdf' => 'required',
'type' => 'required',
])->validate();
}
Thanks in Advance!
If you want to update user profile,without changing his id,you dont need to set specific rule for that.
Without explicitly setting the new user id,it should stay the same.
You can just name the data you want to change like this:
$user->name = request('name');
$user->lastname = request ('lastname);
$user->email = request('email');
...
$user->save();
session()->flash('message','Profile update complete!');
return redirect('/home');
Doing this the data you want will update,but the id will stay the same.
Seems to be some bug.
Adding filed name worked for me:
Rule::unique('users')->ignore($user->id, 'users')

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

Google reCaptcha always resetting with laravel 5.1

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

Resources