Update Query Use in Laravel 12 Example

In Laravel 12, updating records in the database can be achieved using both the Eloquent ORM and the Query Builder. Here’s how you can perform update operations using each method:

1. Using Eloquent ORM

Eloquent provides a fluent and expressive interface for interacting with your database tables.

Updating a Record by ID:

<?php
use App\Models\User;

// Retrieve the user by their primary key (ID)
$user = User::find($id);

// Update attributes
$user->name = 'New Name';
$user->email = 'newemail@example.com';

// Save the changes to the database
$user->save();
?>

Updating Records Based on a Condition:

<?php
use App\Models\User;

// Update all users with the role 'subscriber' to 'member'
User::where('role', 'subscriber')->update(['role' => 'member']);
?>

Using `updateOrCreate` Method:-

The `updateOrCreate` method attempts to find a record matching the given attributes and updates it; if no matching record is found, it creates a new one.

<?php
use App\Models\User;

// Update the user's name if the email exists; otherwise, create a new user
User::updateOrCreate(
['email' => 'johndoe@example.com'],
['name' => 'John Doe', 'role' => 'member']
);
?>

In this example, Laravel searches for a user with the specified email. If found, it updates the name and role; otherwise, it creates a new user with these attributes.

2. Using Query Builder

Laravel’s Query Builder offers a more direct approach to constructing and executing database queries.

Updating Records Based on a Condition:

<?php
use Illuminate\Support\Facades\DB;

// Update users with 'inactive' status to 'active'
DB::table('users')
->where('status', 'inactive')
->update(['status' => 'active']);
?>

Updating Multiple Columns:

<?php
use Illuminate\Support\Facades\DB;

// Update multiple columns for users in a specific department
DB::table('users')
->where('department', 'sales')
->update([
'status' => 'active',
'role' => 'manager'
]);
?>

Incrementing or Decrementing a Column’s Value:

You can increment or decrement a column’s value using the `increment` and `decrement` methods.

<?php
use Illuminate\Support\Facades\DB;

// Increment the 'login_count' by 1 for a specific user
DB::table('users')
->where('id', $id)
->increment('login_count');

// Decrement the 'credits' by 5 for a specific user
DB::table('users')
->where('id', $id)
->decrement('credits', 5);
?>