Laravel update query | Query Builder - Laravel | update query in Laravel eloquent Code Example

In Laravel, you can use the Query Builder to perform update operations on database records. You can specify which records to update based on a condition. Here's how to write an update query in Laravel using the Query Builder:

php
use Illuminate\Support\Facades\DB; // Update records based on a WHERE condition DB::table('your_table_name') ->where('column_name', '=', 'value_to_match') ->update([ 'column_to_update' => 'new_value', // You can add more columns to update as needed ]);

Replace the following placeholders with your actual data:

  • 'your_table_name': The name of the database table in which you want to update records.
  • 'column_name': The name of the column you want to use as a condition.
  • 'value_to_match': The value to match in the specified column to determine which records should be updated.
  • 'column_to_update': The name of the column you want to update.
  • 'new_value': The new value you want to set for the specified column.

You can also use other comparison operators in the where clause, such as <, <=, >, >=, and <> (not equal), depending on your specific needs.

Here's an example of updating records in a users table where the status column is equal to 'active' and setting the role column to 'admin' for those records:

php
use Illuminate\Support\Facades\DB; DB::table('users') ->where('status', '=', 'active') ->update([ 'role' => 'admin', ]);

This code will update all records in the users table where the status column is equal to 'active' and set their role column to 'admin'.

You can chain multiple where conditions and update multiple columns as needed to perform more complex update operations on your database records.

Comments