How to toggle a boolean value database field in laravel?

Member

by jasen , in category: PHP Frameworks , 10 months ago

How to toggle a boolean value database field in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 10 months ago

@jasen 

To toggle a boolean value in a database field in Laravel, you can use the toggle() method provided by Eloquent. This method will toggle the boolean value of the specified field.


Assuming you have a model called User with a boolean field named is_active, you can toggle its value like this:

1
2
3
$user = User::find($userId);
$user->is_active = !$user->is_active;
$user->save();


Alternatively, you can simplify the process by using the toggle() method directly on the model:

1
2
$user = User::find($userId);
$user->toggle('is_active');


This will toggle the boolean value of the is_active field for the user with the given ID.


Remember to replace User with the appropriate model name and is_active with the actual field name in your database schema.

Related Threads:

How to insert a boolean value to a table in postgresql?
How to make a button affect a boolean value in html?
How to convert string to boolean in laravel migration?
How to update field by multiply field value in mongodb?
How to get value from customer phone field in shopify?
How display a product custom field value in woocommerce?