How to update an exiting column on laravel?

by lindsey.homenick , in category: PHP Frameworks , 2 days ago

How to update an exiting column on laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , a day ago

@lindsey.homenick 

To update an existing column in Laravel, you can use the update method on the model that corresponds to the table where the column is located. Here's an example of how you can update an existing column in Laravel:

  1. First, retrieve the record that you want to update. You can do this by using the find method to find the record by its primary key:
1
$record = YourModel::find($id);


  1. Once you have retrieved the record, you can update the column by directly assigning a new value to it and then calling the save method on the model:
1
2
$record->column_name = 'new value';
$record->save();


  1. Alternatively, you can also use the update method on the model, which allows you to update multiple columns at once. You can pass an array of key-value pairs where the keys represent the column names and the values represent the new values:
1
2
3
4
YourModel::where('id', $id)->update([
    'column_name' => 'new value',
    'another_column' => 'another value'
]);


Remember to replace YourModel with the name of your model class and column_name with the name of the column you want to update. Replace $id with the ID of the record you want to update.


That's it! Your existing column should now be updated with the new value.