I use username
as an id
to login and made username and email as unique.
Whenever I made username and email, validation rules check coming data and there is no problem with it because username
and email
would be new and unique.
The problem occurs when I update. when I update the attributes, I don't need to change the username mostly but the rules are expecting unique, username
.
what is the best practice for updating unique attributes with validation rules?.
Update user method
public function updateUser($req, $id)
{
$user = User::where('user_id', $id)->firstOrFail();
$user->username = $req->input('username');
$user->password = Hash::make($req->input('password'));
$user->email = $req->input('email');
$user->first_name = $req->input('first_name');
$user->last_name = $req->input('last_name');
$user->phone = $req->input('phone');
$user->emergency_phone = $req->input('emergency_phone');
$user->profile_photo = $req->input('profile_photo');
$user->role = $req->input('role');
$user->status = $req->input('status');
$user->save();
return $this->filterUsers([$user]);
}
Rules
protected $rules = [
'username' => 'required|max:20|unique:users',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required',
// **in Production **
// 'password' => [
// 'required',
// 'min:6',
// 'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\X])(?=.*[!$#%]).*$/',
// 'confirmed'
// ],
/**
* Three of the five rules.
* English uppercase characters (A – Z)
* English lowercase characters (a – z)
* Base 10 digits (0 – 9)
* Non-alphanumeric (For example: !, $, #, or %)
* Unicode characters
*/
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/|min:5',
'role' => 'required'
];