Reputation:
i am working on a settings page were a user sees his prefilled username and email in the input fields. I like to detect (without jQuery 😀) if the user changed the prefilled values on the inputs.
For the password reset fields (not prefilled) i use the follwing logic:
if($request['password'] != ""){
if(!(Hash::check($request['password'], Auth::user()->password))){
return redirect()->back()->with('error', 'Your password does not match with the password you provided.');
}
if(strcmp($request['password'], $request['new_password']) == 0){
return redirect()->back()->with('error', 'New password cannot be same as your old one.');
}
$validation = $request->validate([
'password' => 'required',
'new_password' => 'required|string|min:6|confirmed',
]);
$user->password = bcrypt($request['new_password']);
$user->save();
return redirect()->back()->with('alert-success', 'Password changed
successfully');
}
How can i check if the user changed the prefilled code to use the following procedure:
if($request[''] ????? ""){
$user = Auth::user();
$user->name = $request['name'];
$user->email = $request['email'];
$user->save();
}
Thanks
Upvotes: 0
Views: 1686
Reputation:
after long search i found isDirty()
to check if database informations had changed, but i needed check if the prefilled input has changed before sending, so i added a second action button, now using a switch statement for a more controlled behaviour, like so:
public function profilePost(UserUpdate $request)
{
switch($request->input('action')){
case 'save_user':
$user = Auth::user();
$user->name = $request['name'];
$user->email = $request['email'];
$user->save();
return redirect()->back()->with('alert-success', 'Your profile information changed successfully');
break;
case 'save_password':
if($request['password'] != ""){
if(!(Hash::check($request['password'], Auth::user()->password))){
return redirect()->back()->with('error', 'Your current password does not match with the password you provided.');
}
if(strcmp($request['password'], $request['new_password']) == 0){
return redirect()->back()->with('error', 'New password cannot be same as your current one.');
}
$validation = $request->validate([
'password' => 'required',
'new_password' => 'required|string|min:6|confirmed'
]);
$user = Auth::user();
$user->password = bcrypt($request['new_password']);
$user->save();
return redirect()->back()->with('alert-success', 'Password changed
successfully');
} else {
return redirect()->back()->with('error', 'No Password was changed');
}
break;
}
}
Upvotes: 1
Reputation: 6544
In my opinion, you don't need all this. Just use the following. It will only really update the model if the values changed. If the values did not change (i.e. the submitted data is the same that is already stored in the database), no database query will be made.
$user = Auth::user();
$user->fill($request->only(['name', 'email']));
$user->save();
Upvotes: 2