Skip to content
Advertisement

How to active and inactive boolean in Laravel

I want to know how to make a Boolean data true or false in database whenever my button is clicked. I already can perform a true when button is clicked, I want to know how to make it false. I hope I can get a answer thank you! BTW, this is my first time to post a question here and the source code are from Code With Stein from YT a big credits. Here are some of codes I used.

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

Advertisement

Answer

If you want to make it false (or like toggle), can try swap the value with !

something like this

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

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

I’ve tested here

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

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement