How to insert data in database - Laravel framework

How to insert data in database - Laravel framework


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:

php artisan make:model Product

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:

<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Product extends Model { use HasFactory; protected $table = 'products'; // Table name protected $fillable = ['name', 'price', 'description']; // Allow mass assignment }

Step 3: Insert Data Using Eloquent

Now, insert data into the database:

use App\Models\Product; // Create a new product record Product::create([ 'name' => 'Laptop', 'price' => 1200, 'description' => 'High-performance laptop' ]);

Alternatively, you can use the save() method:

$product = new Product(); $product->name = 'Smartphone'; $product->price = 800; $product->description = 'Latest smartphone model'; $product->save();

2. Insert Data Using Laravel Query Builder

The Query Builder allows inserting data without using models.

use Illuminate\Support\Facades\DB; DB::table('products')->insert([ 'name' => 'Tablet', 'price' => 500, 'description' => 'Portable and powerful tablet' ]);

For multiple records:

DB::table('products')->insert([ ['name' => 'Headphones', 'price' => 150, 'description' => 'Noise-canceling headphones'], ['name' => 'Monitor', 'price' => 300, 'description' => '4K Ultra HD display'] ]);

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

php artisan make:controller ProductController

Step 2: Add Store Function in Controller

Modify app/Http/Controllers/ProductController.php:

use Illuminate\Http\Request; use App\Models\Product; class ProductController extends Controller { public function store(Request $request) { // Validate request $request->validate([ 'name' => 'required|string|max:255', 'price' => 'required|numeric', 'description' => 'nullable|string', ]); // Insert data Product::create([ 'name' => $request->name, 'price' => $request->price, 'description' => $request->description, ]); return back()->with('success', 'Product added successfully!'); } }

Step 3: Create a Form in Blade File

In resources/views/products/create.blade.php:

<form action="{{ route('products.store') }}" method="POST"> @csrf <label>Name:</label> <input type="text" name="name" required> <label>Price:</label> <input type="number" name="price" required> <label>Description:</label> <textarea name="description"></textarea> <button type="submit">Add Product</button> </form>

Step 4: Define Route in routes/web.php

use App\Http\Controllers\ProductController; Route::post('/products/store', [ProductController::class, 'store'])->name('products.store');

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)

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close