Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel update only single row

I am having a trouble updating my single record in database with laravel.

When i run this method and give requestparams only "name" then the other fields are going to be blank in database. How to keep the values that are not specified in the requestparams?.

public function update(Request $request, $id)
{
    $user = User::find($id);
    if(!is_null($user)){
        $user->name = $request->input('name');
        $user->email = $request->input('email');
        $user->password = $request->input('password');
        $user->save();
    }else{
        $data = array('msg' => 'The user, you want to update, does not exist', 'error' => true);
        echo json_encode($data);
    }
}
like image 749
anduplats Avatar asked Dec 19 '22 07:12

anduplats


1 Answers

You can use the update method with the request input directly. This will only update the inputs provided.

$user->update($request->only(['name', 'email', 'password']));

Few things to note though. You're trying to update the password directly from the input. Which is a bad practise and might be wrong since laravel uses bcrypt by default to store passwords. Secondly make sure you set the $fillable property in the model to protect against mass-assignment.

protected $fillable = [
    'name', 'email', 'password'
];

Also you can use a mutator to hash the password like so.

public function setPasswordAttribute($value)
{
    $this->attributes['password'] = bcrypt($value);
}
like image 58
Sandeesh Avatar answered Jan 02 '23 15:01

Sandeesh