Laravel Updating Records
Updating a record changes the stored values of a row. The update method changes the row and saves it at once.
Change one field
This line renames the Buy milk task.
Task::where('title', 'Buy milk')
->update(['title' => 'Buy oat milk']);
return Task::orderBy('id')->pluck('title')->implode(', ');Mark a task done
This line marks Call Ana as done. Updating a record changes the stored values of a row.
Task::where('title', 'Call Ana')->update(['done' => true]);
return Task::where('done', false)->orderBy('title')
->pluck('title')->implode(', ');Change, then save
These lines mark Buy milk as done and save it.
$task = Task::where('title', 'Buy milk')->first();
$task->done = true;
$task->save();
return Task::where('done', false)->orderBy('title')
->pluck('title')->implode(', ');Example
Route::get('/tasks/rename', function () {
Task::where('title', 'Buy milk')
->update(['title' => 'Buy oat milk']);
return Task::orderBy('id')->pluck('title')->implode(', ');
});Key points
- Update: to change the stored values of a row.
- Use update() on a query to change matching rows at once.
- Use save() after changing a field on one Task.
- Use where() before update() to choose the rows.
In this example, the route answers at /tasks/rename. The where call finds the Buy milk task. The update call renames it to Buy oat milk. The next line reads every title in stored order. The joined titles are Buy oat milk, Write report, and Call Ana.
Note
update() without where() changes every row in the table.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does update() do without where()?