How to toggle a boolean value database field in laravel?

Member

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

How to toggle a boolean value database field in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 3 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.