Creating & Updating Records
Insert, update and delete rows through Eloquent models.
Syntax
Post::create(['title' => 'Hello']);Eloquent turns database writes into simple method calls:
Post::create([...])— insert a new row.$post->update([...])— change an existing row.$post->delete()— remove it.
Mass assignment (passing an array) requires listing the columns in the model's $fillable property.
Example
// Create
$post = Post::create(['title' => 'Hello', 'body' => 'World']);
// Update
$post->update(['title' => 'Updated title']);
// Delete
$post->delete();When to use it
- A product controller's store() method calls Product::create($request->validated()) to insert a new row using only the validated form fields.
- An API update endpoint uses $model->fill($data)->save() pattern to apply partial updates, keeping existing fields unchanged.
- A soft-delete feature lets administrators remove posts from the public listing with delete() while still being able to restore them later via restore().
More examples
Create and firstOrCreate
create() inserts a new model using mass assignment; firstOrCreate() is idempotent — it finds an existing record or creates one if absent.
// Insert a new row
$post = Post::create([
'title' => 'Hello World',
'body' => 'My first post.',
'status' => 'draft',
]);
// Find by attributes or create if not found
$tag = Tag::firstOrCreate(
['slug' => 'laravel'],
['name' => 'Laravel']
);Update a single model or many rows
Instance update() fires Eloquent events; Builder update() performs a SQL UPDATE directly for bulk operations where events are not needed.
// Update one model via instance
$post = Post::findOrFail($id);
$post->update(['title' => 'Updated Title', 'status' => 'published']);
// Bulk update without loading models (no events fired)
Post::where('status', 'draft')
->where('created_at', '<', now()->subDays(30))
->update(['status' => 'archived']);Soft delete and restore
The SoftDeletes trait marks records with a deleted_at timestamp instead of removing them, enabling withTrashed() queries and restore().
// Model must use SoftDeletes trait + deleted_at column
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
}
// Delete (sets deleted_at, row stays in DB)
$post->delete();
// Query includes soft-deleted records
Post::withTrashed()->find($id);
// Restore
Post::withTrashed()->find($id)->restore();
// Permanently remove
$post->forceDelete();
Discussion