如何在 Laravel 中启用和禁用布尔值

How to active and inactive boolean in Laravel

我想知道如何在单击我的按钮时使数据库中的布尔数据为真或假。 单击按钮时我已经可以执行 true,我想知道如何使其变为 false。希望能得到解答谢谢!顺便说一句,这是我第一次在这里 post 提问,源代码来自 YT 的 Code With Stein。 这是我使用的一些代码。

My code for my update form

<form method="POST" action="/{{ $todo->id }}">
 @csrf
            @method('PATCH')
            <button class="py-2 px-2 bg-green-500 text-white rounded-xl" id="show">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
            <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
            </svg>
            </button>
            </form>

My code for route

Route::patch('/{todo}', [TodoController::class, 'update']);

My code for my controller

  public function update(Todo $todo) {
    $todo->update(['isDone' => true]);
    return redirect('/')->with('msg1', 'Marked as done!');;

}    

UI change when I the button clicked

        <div 
        @class([
            'py-4 flex items-center border-b border-gray-300 px-3',
            $todo->isDone ? 'bg-green-200' : ''
            
        ])
        >

Screenshot of UI

如果你想让它变成 false(或者像 toggle),可以尝试用 !

交换值

像这样

// "$todo->isDone" value is false
$todo = Todo::create(['isDone' => false]);

// Since ! means "not" in logical operator, so !false = true
$todo->update(['isDone' => !$todo->isDone]);

我在这里测试过

https://web.tinkerwell.app/#/snippets/dc8a7b9f-59a6-4c07-84ca-1bb2fc8c1da4

就用这个控制器代替

public function update(Todo $todo) {
 $todo->update(['isDone' => !$todo->isDone]);
 return redirect('/')->with('msg1', 'Marked as done!');;
}