Laravel Eloquent ORM  

Laravel’s Eloquent ORM (Object Relational Mapping) is one of the most powerful and developer-friendly features of the framework. 
It allows you to interact with your database using simple PHP objects, instead of writing complex SQL queries. 

This deep dive will help you fully understand how Eloquent works and how to use it effectively in real projects. 

1. What is Eloquent ORM? 

Eloquent is Laravel’s built-in ORM that provides: 

  • Object-based database interaction 
  • Cleaner and readable code 
  • Automatic SQL query handling 
  • Relationship mapping 
  • Built-in CRUD operations 

Each database table = one Model 
Example: products table → Product model 

Eloquent follows Active Record Pattern, meaning each model object directly manages: 

  • Inserting 
  • Updating 
  • Deleting 
  • Querying 

2. Creating a Model 

php artisan make:model Product 
 

This creates: 
app/Models/Product.php 

A basic model looks like: 

class Product extends Model 

    protected $fillable = [‘name’, ‘price’, ‘description’]; 

 

$fillable 

Prevents mass assignment vulnerability. 

3. Basic CRUD Operations 

Create Data 

Product::create([ 
    ‘name’ => ‘Laptop’, 
    ‘price’ => 50000, 
    ‘description’ => ‘High performance laptop’ 
]); 
 

Read Data 

$products = Product::all(); // Returns all records 
$product = Product::find(1); // Fetch by ID 
$product = Product::where(‘price’, ‘>’, 10000)->get(); 
 

Update Data 

$product = Product::find(1); 
$product->update([‘price’ => 55000]); 
 

Delete Data 

$product = Product::find(1); 
$product->delete(); 
 

4. Eloquent Query Builder (Advanced Queries) 

Eloquent supports beautiful, chainable queries: 

$expensive = Product::where(‘price’, ‘>’, 20000) 
                    ->orderBy(‘price’, ‘desc’) 
                    ->take(5) 
                    ->get(); 
 

Common methods: 

  • where() 
  • orWhere() 
  • orderBy() 
  • limit() 
  • paginate() 

Example: Pagination 

$products = Product::paginate(10); 
 

5. Eloquent Relationships (Very Important) 

Databases have relations — Eloquent makes them easy. 

5.1 One-to-One 

Example: User ↔ Profile 

User.php 

public function profile() 

    return $this->hasOne(Profile::class); 

 

5.2 One-to-Many 

Example: Category → many Products 

Category.php 

public function products() 

    return $this->hasMany(Product::class); 

 

Product.php 

public function category() 

    return $this->belongsTo(Category::class); 

 

5.3 Many-to-Many 

Example: Students ↔ Courses 

Student.php 

public function courses() 

    return $this->belongsToMany(Course::class); 

 

Laravel automatically manages pivot table: course_student. 

5.4 Polymorphic Relationships 

Example: Comments on Posts or Videos 

Comment.php 

public function commentable() 

    return $this->morphTo(); 

 

6. Eager Loading vs Lazy Loading 

Lazy Loading (default → multiple queries run) 

$users = User::all(); 
foreach ($users as $user) { 
    echo $user->posts;  // triggers new query each time 

 

Eager Loading (best performance) 

$users = User::with(‘posts’)->get(); 
 

🔥 Reduces N+1 query problem → much faster. 

7. Mutators & Accessors 

Modify data before saving or after retrieving. 

Accessor (get value) 

public function getNameAttribute($value) 

    return ucfirst($value); 

 

Mutator (set value) 

public function setNameAttribute($value) 

    $this->attributes[‘name’] = strtolower($value); 

 

8. Soft Deletes 

Allows “invisible” deletion without removing data from DB. 

Enable 

use SoftDeletes; 
 

Migration: 

$table->softDeletes(); 
 

9. Timestamps Handling 

Laravel auto-manages: 

  • created_at 
  • updated_at 

Disable timestamps: 

public $timestamps = false; 
 

10. Eloquent API Resources (For APIs) 

Clean API responses: 

php artisan make:resource ProductResource 
 

Example: 

return new ProductResource($product); 
 

Improves formatting and structure of JSON responses.