Laravel 8 Database & Eloquent ORM Explained
Laravel provides a powerful database system using Eloquent ORM (Object-Relational Mapping), making it easy to interact with databases.
1. Database Configuration
Laravel uses .env file for database settings.
Open .env and update:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=
Run Migration to check if the connection works:
php artisan migrate
2. Creating a Model & Migration
Eloquent uses Models to interact with database tables.
Run this command to create a model with a migration file:
php artisan make:model Product -m
This creates:
- Model:
app/Models/Product.php - Migration:
database/migrations/xxxx_xx_xx_create_products_table.php
File: database/migrations/xxxx_xx_xx_create_products_table.php
Modify the up() method:
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->decimal('price', 8, 2);
$table->text('description')->nullable();
$table->timestamps();
});
}
Run Migration to create the table:
php artisan migrate
3. Eloquent Model Setup
File: app/Models/Product.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = ['name', 'price', 'description']; // Mass assignable fields
}
4. Performing CRUD Operations
Eloquent makes it easy to perform Create, Read, Update, Delete (CRUD) operations.
a) Insert Data (Create)
Using Eloquent
use App\Models\Product;
Product::create([
'name' => 'Laptop',
'price' => 49999.99,
'description' => 'A high-performance laptop'
]);
Using save() Method
$product = new Product();
$product->name = "Smartphone";
$product->price = 19999.99;
$product->description = "A powerful smartphone";
$product->save();
b) Fetch Data (Read)
Get all records
$products = Product::all();
Get a single record by ID
$product = Product::find(1);
Find by a specific column
$product = Product::where('name', 'Laptop')->first();
Looping through records
foreach (Product::all() as $product) {
echo $product->name . " - ₹" . $product->price . "<br>";
}
c) Update Data
Update using find()
$product = Product::find(1);
$product->price = 47999.99;
$product->save();
Update using update()
Product::where('name', 'Laptop')->update(['price' => 45999.99]);
d) Delete Data
Delete a record
$product = Product::find(1);
$product->delete();
Delete using where()
Product::where('name', 'Smartphone')->delete();
Delete all records
Product::truncate();
5. Eloquent Relationships
Eloquent makes handling relationships easy.
a) One-to-One Relationship
A User has one Profile.
Migration: users Table
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Migration: profiles Table
Schema::create('profiles', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id')->unique();
$table->text('bio');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
Model: User.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}
Model: Profile.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Fetching User Profile
$user = User::find(1);
echo $user->profile->bio;
b) One-to-Many Relationship
A Category has many Products.
Model: Category.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function products()
{
return $this->hasMany(Product::class);
}
}
Fetching All Products in a Category
$category = Category::find(1);
foreach ($category->products as $product) {
echo $product->name;
}
c) Many-to-Many Relationship
A User has many Roles, and a Role belongs to many Users.
Pivot Table Migration
Schema::create('role_user', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('role_id');
$table->timestamps();
});
Model: User.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class);
}
}
Model: Role.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
}
Assign Role to a User
$user = User::find(1);
$user->roles()->attach(2); // Assign role with ID 2
Fetching Roles for a User
$user = User::find(1);
foreach ($user->roles as $role) {
echo $role->name;
}
6. Query Builder vs. Eloquent
Laravel provides Query Builder as an alternative to Eloquent.
Using Query Builder
use Illuminate\Support\Facades\DB;
$products = DB::table('products')->get();
Using Eloquent
$products = Product::all();
🚀 Eloquent is recommended as it provides a more readable and maintainable approach.
7. Database Seeding
Seeding allows inserting dummy data.
Create a Seeder
php artisan make:seeder ProductSeeder
File: database/seeders/ProductSeeder.php
use Illuminate\Database\Seeder;
use App\Models\Product;
class ProductSeeder extends Seeder
{
public function run()
{
Product::create([
'name' => 'Tablet',
'price' => 29999.99,
'description' => 'A lightweight tablet'
]);
}
}
Run Seeder
php artisan db:seed --class=ProductSeeder
Conclusion
Eloquent ORM makes database handling simple, fast, and readable in Laravel. 🚀✨
Need any clarification? 😊
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
