Laravel how to update the table

Laravel: Update a Table with an Example: Learn how to use Eloquent and Query Builder to update a table in Laravel.

Updating Records in a Database Table in Laravel

Updating records in a database table in Laravel is done using the update() method. This method accepts an array of column and value pairs representing the columns that need to be updated. The array should contain the column names as keys and their new values as values.

You can also use the update() method to update multiple records at once. To do this, pass an array of arrays to the method. Each array should contain the column names and their new values. The following example shows how to update multiple records at once:


$updated = DB::table('users')
            ->where('votes', '>', 100)
            ->update([
                'status' => 'active',
                'points' => DB::raw('points + 1'),
            ]);

The above code updates the status and points columns of all the users that have more than 100 votes. The points column is incremented by 1.

You can also use the increment() and decrement() methods to increment or decrement a column value. These methods accept the column name as the first argument and the amount to increment/decrement as the second argument. The following example shows how to use the increment() method:


$affected = DB::table('users')
            ->where('votes', '>', 100)
            ->increment('points', 1);

The above code increments the points column of all the users that have more than 100 votes by 1.

You can also use the updateOrInsert() method to update or insert a record into the database table. This method accepts two parameters: an array of column and value pairs and another array of where conditions. If a user matching the where conditions is found, the record will be updated with the column and value pairs. Otherwise, a new record will be inserted into the table. The following example shows how to use the updateOrInsert() method:


$affected = DB::table('users')
            ->updateOrInsert(
                ['name' => 'John', 'age' => 30],
                ['status' => 'active']
            );

The above code checks if a user with the name John and age 30 exists in the table. If a user is found, the status column is updated with the value active. Otherwise, a new record is inserted into the table with the name John, age 30 and status active.

Answers (0)