Home > Blockchain >  Change user status from checkbox laravel
Change user status from checkbox laravel

Time:11-01

I want to change the user status with a checkbox. If the checkbox is marked, the status should be one. Right now my change status function in the controller doesn't change anything at all. How do I make sure he sees the checkbox as a value, and that the checkbox marker changes when the value is 1. This is what I have thus far:

in my view:

<form action="{{ route('users.change_status', $user) }}" class="form" method="post">
                                {{ csrf_field() }}
                                @method('PATCH')
                                <label>body</label>
                                <input type="checkbox" class="form-control" name="body" value="{{$user->status}}">
                                <div class="form-group">
                                    <button type="submit" class="button is-link is-outlined">Update</button>
                                </div>
                            </form>

In my userController:

public function index()
    {
        $users = User::get();
        return view('users',compact('users'));
    }


    public function change_status(Request $request, User $user)
    {
        dd($user);

        // Validate posted form data
        $validated = $request->validate([
            'status' => 'required',
        ]);

        if (!$validated) { return redirect()->back();}
        $user->update($request->all());

        return redirect()->back();

    }

And my routes in web.php:

Route::get('/users', [UserController::class, 'index'])->name('users.index');
Route::patch('/change_status', [UserController::class, 'change_status'])->name('users.change_status');

CodePudding user response:

use Route Model Binding

Route::patch('/change_status/{user}', [UserController::class, 'change_status'])->name('users.change_status');

CodePudding user response:

You will have to use blade's if statements to add a checked attribute on the checkbox if the status is set, it can be as simple as checking if the value is truthy, which 1 is.

<form action="{{ route('users.change_status', $user) }}" class="form" method="post">
    {{ csrf_field() }}
    @method('PATCH')
    <label>body</label>
    <input type="checkbox" class="form-control" name="body" value="{{$user->status}}" @if($user->status) checked @endif>
    <div hljs-string">">
        <button type="submit" hljs-string">">Update</button>
    </div>
</form>

Here's a quick working demo.

And as @Mohsen said, make sure you pass in the user so your controller has access to it.

  • Related