Performance: CRUD with Eloquent
This affects server response time and database query efficiency, impacting how fast data changes reflect on the page.
<?php User::where('status', '!=', 'active')->update(['status' => 'active']); ?>
<?php $users = User::all(); foreach ($users as $u) { $u->update(['status' => 'active']); } ?>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Loading all records and updating in loop | High (loads all data) | N/A (server-side) | N/A (server-side) | [X] Bad |
| Bulk update with single query | Low (no DOM impact) | N/A (server-side) | N/A (server-side) | [OK] Good |
create()create() method in Eloquent is designed to add a new record to the database by passing an array of attributes.find() retrieves a record, delete() removes a record, and update() modifies an existing record. None of these add new records.create() -> Option Acreate() [OK]User::find($id) is correct.User->find($id) is invalid because User is a class, not an object. findById() does not exist. User.find() is not PHP syntax.$user = User::find($id); -> Option C$user = User::find(5);
if ($user) {
$user->name = 'Alice';
$user->save();
echo 'Updated';
} else {
echo 'Not found';
}
User::find(5) returns an Eloquent model instance, making $user truthy.if ($user) condition passes, so name is set to 'Alice', save() persists it to the database, and 'Updated' is echoed.$user = User::find($id);
$user->delete($id);
delete() is called on the model instance without any arguments to remove that record.$id to delete(), which expects no parameters. This causes an error.$user = User::find($id);checks if
if ($user && !empty($newEmail)) {
$user->email = $newEmail;
$user->save();
}
$user exists and $newEmail is not empty before updating, preventing errors or empty updates.$user = User::find($id);skips user existence check, risking errors if user is null.
if ($newEmail) {
$user->email = $newEmail;
$user->save();
}
$user = User::findOrFail($id);uses
$user->email = $newEmail;
$user->save();
findOrFail() which throws exception if user missing, no email empty check. $user = User::where('id', $id)->update(['email' => $newEmail]); updates directly but does not check if $newEmail is empty.$user = User::find($id);-> Option B
if ($user && !empty($newEmail)) {
$user->email = $newEmail;
$user->save();
}
Pass the test and this pattern moves unknown