Home » Php » php – How to update database record in Laravel

php – How to update database record in Laravel

Posted by: admin February 25, 2020 Leave a comment

Questions:

i use this rout ==> Route::put(‘update/{id}’,’[email protected]’);

And i use this function

public function update(Request $request, $id)
   {

    $input=[
        'name' => $request->name,
        'email' => $request->email,
        'password' => $request->password,
    ];
    $update = DB::table('users')->where('id', $id)->update($input);
    if ($update) {
        dd('updated');
    }
    else{
        dd('error');

   }
}

but i see a error.

How to&Answers:

Try this

$this->validate($request, [
    'user_name' => 'required|max:255',
    'email' => 'required',
    'password' => 'required|min:8'
]);
    $user = User::findOrFail($id);
    $input = $request->all();
    $user->fill($input)->save();

Or try this

$this->validate($request, [
    'user_name' => 'required|max:255',
    'email' => 'required',
    'password' => 'required|min:8'
]);
    $user = User::findOrFail($id);
    $user->user_name = $request->input('user_name');
    $user->email = $request->input('email');
    $user->password = $request->input('password');
    $user->save();

Both are correct ways for update.

Answer:

Your code looks fine.

But I think you are updating the same values. If you try to update with the same values, it will return 0. otherwise 1.

So I suggest you to check if this is the case.