Laravel Updating a record - laravel

I'm having troubles updating a record. I have a page where users can register, this works flawlessly and has 4 fields: email, username, password and confirm password. This is a simple registration page and I dont want to turn off the visitors by presenting a lot of stuff to be filled out like full name and country, so these 2 fields can be updated on their "update profile" page. The profile page is separated into areas, the main area is a single form where only these 2 fields can be updated so no username, email, password fields here - only fullname and country.
Controller Update Profile Code
$user = User::find($id);
$user->fullname = Input::get('fullname');
$user->country = Input::get('country');
if (!$user->save())
{
return Redirect::to('edit-profile')->withInput()->withErrors($user->errors());
} else {
return Redirect::to('edit-profile')->withMessage('Profile successfully updated!');
}
My User Model rules. I'm using Ardent:
public static $rules = array(
'username' => 'required|between:3,20|unique:users|alpha_dash',
'email' => 'required|email|unique:users',
'password' => 'required|min:5|confirmed',
'password_confirmation' => 'min:5',
'fullname' => 'between:5,50',
'country' => 'between:3,50'
);
Problem here is that it returns an error message saying "Passwords do not match.". So it seems like Laravel is adding the password field in the query and also tries to validate if the passwords match. I do not want to create a separate model or a separate rules for this. How can I solve this?

To make it work when you do not display a password you can test if you are displaying it, then make it a required field, in the controller:
if ($user->exists){
$user::$rules['password'] = (Input::get('password')) ? 'required|min:5|confirmed' : '';
$user::$rules['password_confirmation'] = (Input::get('password')) ? 'required' : '';
}
$user->save();

Related

Laravel create command wont insert a value in database

Hello i am new to Laravel so currently im doing a CRUD. I have created this insert function that works well except one value is never inserted. This is the code below:
public function storeClient(Request $request) {
$request->validate([
'name' => 'required',
'email' => 'required|email',
'phone' => 'nullable',
'age'=>'required',
]);
Client::create($request->all());
dd($request->phone);
return redirect('/')->with('msg', 'Client Saved successfully!.');
}
the phone' => 'nullable', value will not insert in the database unless i update the existing values. I tried this command dd($request->phone); and it shows the correct value from the user input. Any idea why the value will be inserted as null on database?
This is the value output when i make the dd command
I tried this other code which works well but im trying to use the default create() function of laravel. This is the other code i did that works well:
public function storeClient()
{
$client = new Client();
$client->name = request('name');
$client->email = request('email');
$client->phone_number = request('phone');
$client->age = request('age');
$client->save();
return redirect('/')->with('msg','Client Saved successfully!');
}
first i did not like nullable here 'phone' => 'nullable',
then u should see what do you register in your Client table phone_number or phone,
$client->phone_number = request('phone');
i think you should rename your input name phone to phone_number and will work
When you are trying to use default create method the fields names must be same as in database.
$client->phone_number = request('phone');
this line works due to the name you entered manually.
to work with default create method change the name of field in database as phone.

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.

Laravel profile update with e-mail unique:users

I'm new in Laravel. I try to make profile update page... all works good but if I try to apply rule to set email field unique:users I have problem when user try to update for example name and don't want change email.
public function rules()
{
return [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
];
}
I want restrict that user to use the same e-mail that someone else is using... but I want to ignore that if this is the same e-mail already in that user profile and he don't want to change that.
public function updateData(UpdateDataRequest $request)
{
DB::table('users')
->where('id', Auth::user()->id)
->update(array('email' => $request->email, 'name' => $request->name));
return redirect('panel');
}
How to do it right?
This exact situation is used as an example in the docs.
https://laravel.com/docs/5.2/validation#rule-unique
Forcing A Unique Rule To Ignore A Given ID:
Sometimes, you may wish to ignore a given ID during the unique check. For example, consider an "update profile" screen that includes the user's name, e-mail address, and location. Of course, you will want to verify that the e-mail address is unique. However, if the user only changes the name field and not the e-mail field, you do not want a validation error to be thrown because the user is already the owner of the e-mail address. You only want to throw a validation error if the user provides an e-mail address that is already used by a different user. To tell the unique rule to ignore the user's ID, you may pass the ID as the third parameter:
'email' => 'unique:users,email_address,'.$user->id
If your table uses a primary key column name other than id, you may specify it as the fourth parameter:
'email' => 'unique:users,email_address,'.$user->id.',user_id'
In new version. laravel using Rules to ignore a user or record
https://laravel.com/docs/5.8/validation#rule-unique
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
Validator::make($data, [
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
]);
$user->id can be a specific id or the id of current user which is login
try to this validation(Laravel 8.x)
'email' => ['email:rfc','confirmed','unique:App\Models\User,email'],

Laravel validator check existence for multiple fields

I'm creating a user login form where user can use his/her username or email to login with Laravel, so on the backend, I want to validate if the user input is either an existed username or an existed email address, something like
$validator = Validator::make(
array('username_or_email' => $username_or_email),
array('username_or_email' => 'exists:users,username|exists:users,email)
);
but I doubt the above is the correct syntax for it, so how should I write my validator?
Assuming you don't allow # in username you could do it this way:
if (strpos($username_or_email, '#') === false) {
$rule = 'exists:users,username';
}
else {
$rule = 'exists:users,email;
}
$validator = Validator::make(
array('username_or_email' => $username_or_email),
array('username_or_email' => $rule)
);

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