How to Insert Data into a MySQL Database in Laravel
Laravel provides multiple ways to insert data into a database using Eloquent ORM and Query Builder. Let’s go step by step:
1. Insert Data Using Eloquent ORM
Eloquent makes inserting data into the database easy. Here’s how:
Step 1: Define a Model
If you haven’t created a model yet, use this command:
It will generate a Product.php
model inside the app/Models
directory.
Step 2: Configure the Model
Open app/Models/Product.php
and define the table and fillable fields:
Step 3: Insert Data Using Eloquent
Now, insert data into the database:
Alternatively, you can use the save()
method:
2. Insert Data Using Laravel Query Builder
The Query Builder allows inserting data without using models.
For multiple records:
3. Insert Data from a Form (Example with Controller & Request Validation)
If you're inserting data from a form, follow these steps:
Step 1: Create a Controller
Step 2: Add Store Function in Controller
Modify app/Http/Controllers/ProductController.php
:
Step 3: Create a Form in Blade File
In resources/views/products/create.blade.php
:
Step 4: Define Route in routes/web.php
Final Thoughts
Laravel provides flexible ways to insert data into a MySQL database:
✅ Eloquent ORM (Recommended for clean and readable code)
✅ Query Builder (Useful for direct SQL-like operations)
✅ Form Handling (For inserting user input into the database with validation)