CRUD with Eloquent
Create, read, update and delete records with stunningly simple code — the core of any app.
What you will learn
- Perform full CRUD with Eloquent
- Wire it into controller methods
- Build a resource
CRUD, the Eloquent way
CRUD stands for the four things every database app does: Create, Read, Update and Delete. Here are all four with Eloquent — notice how short each one is:
// CREATE
$product = Product::create([
'name' => $request->input('name'),
'price' => $request->input('price'),
]);
// READ
$all = Product::all();
$one = Product::find($id);
// UPDATE
$product = Product::find($id);
$product->price = 999;
$product->save();
// DELETE
Product::find($id)->delete();Going block by block: CREATE — Product::create([...]) makes a brand-new row from the submitted values and saves it in one step. READ — Product::all() gets every product, while Product::find($id) gets one by its id. UPDATE — you first find the record, change a property like $product->price = 999, then call $product->save() to write the change. DELETE — Product::find($id)->delete() finds the record and removes it. That is the entire lifecycle of a record.
Let us follow one real product all the way through, with actual values:
// CREATE a real product
$p = Product::create(['name' => 'Keyboard', 'price' => 499]);
echo $p->id; // 1 (Laravel gives the new row an id)
// READ it back
$found = Product::find(1);
echo $found->name; // Keyboard
// UPDATE its price
$found->price = 599;
$found->save(); // the price in the database is now 599
// DELETE it
Product::find(1)->delete(); // the Keyboard row is goneNote: Output: 1 Keyboard We created a Keyboard for 499, Laravel gave it id 1, we read its name back, raised its price to 599, then deleted it — the full create-read-update-delete journey of one record.
The four CRUD steps, in the order an app uses them:
- Create a record from user input with
Product::create([...]). - Read records back with
Product::all()(many) orProduct::find($id)(one). - Update a record by finding it, changing a property, and calling
save(). - Delete a record with
find($id)->delete()when it is no longer needed.
Compare this to the raw PDO prepared statements you wrote — Eloquent does the same safely, in a fraction of the code.
Note: For create() to work, list the allowed fields in the model’s $fillable array (e.g. protected $fillable = ['name', 'price'];) — a safety feature called mass-assignment protection.
Tip: Laravel can generate all CRUD routes at once with a resource controller: php artisan make:controller ProductController --resource plus Route::resource('products', ProductController::class).
Q. Which Eloquent call creates a new record?
✍️ Practice
- Build create, read, update and delete using Eloquent in a controller.
- Wire each to a route and a Blade view.
🏠 Homework
- Build full CRUD for a “tasks” resource with Eloquent.