Search code examples
laravelhttpput

couldn't update one field in laravel


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 class="border px-4 py-2">
                                <form  method="POST" action="{{route('users.status', $user)}}">
                                    @csrf
                                    <input type="hidden" name="_method" value="put"/>
                                    <button type="submit"
                                    class="{{ $user->is_active==1 ? "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


Solution

  • 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->save();
        } 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');
    }