Home > OS >  couldn't update one field in laravel
couldn't update one field in laravel

Time:03-13

this is the route in web.php:

 Route::put('/users.status', [\App\Http\Controllers\dashboard\UsersController::class, 'status'])->name('users.status');

and here is the code in Controller:

public function status(User $user) {
              try{
                $user->is_active = 1;
                $user->update();
//$user->update(['is_active' => 1 ]);
               }catch (\Exception $ex) {
                return redirect()->route('users.index')->with('status', "you couldn't update this record");
            }

            return redirect()->route('users.index')->with('status', 'User Updated successfully');
    }

here is the code in a view, it just a button, when click on it, I need to change the status:

 <td >
                                <form  method="POST" action="{{route('users.status', $user)}}">
                                    @csrf
                                    <input type="hidden" name="_method" value="put"/>
                                    <button type="submit"
                                    bg-green-500" : "bg-red-500" }} hover:bg-red-700 text-white font-bold py-1 px-1 rounded">
                                        {{$user->is_active==1 ? "Active" : "Inactive"}}
                                    </button>
                                </form>
                            </td>

after the button above has clicked, give me this message:

User Updated successfully

but nothing updated in database

CodePudding user response:

First which User you are trying to fetch from route to controller method? You are trying to inject a User $user object to controller method but you did not specified a user param on route definition.

And on the update part; after you set $user->is_active = 1; you need to run $user->save();

So; you need to add a user param to your route:

Route::put('/users/{user}/status', [\App\Http\Controllers\dashboard\UsersController::class, 'status'])->name('users.status');

and run save() method on updated $user ;

public function status(User $user)
{
    try {
        $user->is_active = 1;
        $user->update();
    } catch (\Exception $ex) {
        return redirect()->route('users.index')->with('status', "you couldn't update this record");
    }

    return redirect()->route('users.index')->with('status', 'User Updated successfully');
}

CodePudding user response:

You should call $user->save(); not $user->update();
Also, you can call $user->update(['is_active'=>1]); to have only one line of code.

  • Related