Laravel, Forcing A Unique Rule To Ignore A Given ID - laravel

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

Related

How to get first name and last name from facebook?

I have tried implementing first name and last name of the person trying to authenticate from facebook. I have seen lots of tutorials and followed them accordingly but couldn't get it.
I have tried
$user = Member::create([
'first_name'=> $providerUser->getFirstName(),
'last_name'=>$providerUser->getLastName(),
'email' => $providerUser->getEmail(),
'profilepic'=>$providerUser->getAvatar(),
'password' => md5(rand(1,10000)),
]);
I assumed the provider you use is socialite, to get last name ans first name you can use $providerUser->user['first_name'] and $providerUser->user['last_name']
So based your code:
$user = Member::create([
'first_name'=> $providerUser->user['first_name'],
'last_name'=>$providerUser->user['last_name'],
'email' => $providerUser->getEmail(),
'profilepic'=>$providerUser->getAvatar(),
'password' => md5(rand(1,10000)),
]);

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

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

Password with FirstOrCreate

I want to use FirstOrCreate for a new user.
Like that:
$user = User::FirstOrCreate([
'name' => $request->username,
'email' => $request->email,
'password' => User::generatePassword()
]);
generatePassword() just generate a random 8 chars string string.
Thing is is doesn't work because it's looking for a user that has this password value.
So, it works when there is no user with this email, but when there is it gives me a constraint error.
What should be the cleanest way to fix it???
You've made a grammatical error. ::firstOrCreate searches based on criteria provided, and if it's not found, it will create the database entry and return the model with that data. ::firstOrNew does that without saving the model automatically.
So, you would want this.
$user = User::firstOrNew([
'email' => $request->email,
]);
We do not include name or password because we are not checking to see if Josh with josh#stackoverflow.com using password foobar123 exists, we just want to know if josh#stackoverflow.com has an account.
Your controller logic seems a bit weird because we would first want to validate that information before creating a model, but I'll roll with it.
$user = User::firstOrNew([
'email' => $request->email,
]);
// This model does not have a DB record.
if (!$user->exists)
{
$user->name = $request->username;
$user->password = User::generatePassword();
$user->save();
}
return $user;
With that logic, we find a record based on email. If the record exists, we pass it. If it does not, we assign it a username and generate a password for it before creating the record and then pass it.

Resources