• Fri, Mar 2026

Eloquent ORM Basics: Laravel’s Powerful Way to Work with Databases

Eloquent ORM Basics: Laravel’s Powerful Way to Work with Databases

This in-depth tutorial introduces you to Laravel’s Eloquent ORM, the framework’s expressive and intuitive way of interacting with databases. You’ll learn how to create models, perform CRUD operations, define relationships, and harness advanced querying power. Packed with step-by-step code examples, practical tips, and best practices, this guide is perfect for beginners eager to master Laravel’s da

Introduction

Laravel’s Eloquent ORM (Object Relational Mapper) is one of the most powerful features of the framework. Instead of writing raw SQL queries, you can interact with your database using clean and expressive PHP syntax.

With Eloquent, each table in your database has a corresponding "Model" that you use to interact with that table. If you’ve ever struggled with repetitive SQL queries, you’ll find Eloquent a breath of fresh air.

What is an ORM?

ORM stands for Object Relational Mapper. It is a programming technique that allows you to query and manipulate data using object-oriented programming instead of raw SQL.

Benefits of ORM

  • Cleaner and more readable code
  • Automatic mapping between tables and classes
  • Database-agnostic code (works across MySQL, PostgreSQL, SQLite, etc.)
  • Built-in relationship management

Creating Your First Eloquent Model

In Laravel, models live inside the app/Models directory. Let’s create a User model:


php artisan make:model User
    

This generates app/Models/User.php:


namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    // By default, this model is linked to the "users" table
}
    

Basic Eloquent Conventions

Eloquent follows a set of naming conventions to reduce configuration:

ConventionDescriptionExample
Table NamesPlural snake_case of the model nameModel: User → Table: users
Primary KeyBy default named "id"$table->id();
TimestampsEloquent expects created_at & updated_at columns$table->timestamps();

CRUD with Eloquent

1. Create


// Insert a new user
$user = new User();
$user->name = 'John Doe';
$user->email = 'john@example.com';
$user->save();
    

2. Read


// Fetch all users
$users = User::all();

// Fetch by ID
$user = User::find(1);

// Fetch by condition
$user = User::where('email', 'john@example.com')->first();
    

3. Update


$user = User::find(1);
$user->name = 'Updated Name';
$user->save();
    

4. Delete


$user = User::find(1);
$user->delete();
    

Mass Assignment

Instead of assigning each attribute one by one, you can use mass assignment:


User::create([
    'name' => 'Alice',
    'email' => 'alice@example.com',
    'password' => bcrypt('password'),
]);
    

Make sure to define $fillable in your model:


class User extends Model
{
    protected $fillable = ['name', 'email', 'password'];
}
    

Querying with Eloquent

Basic Where Clauses


$users = User::where('is_active', 1)->get();
    

Chaining


$users = User::where('is_active', 1)
              ->where('role', 'admin')
              ->orderBy('created_at', 'desc')
              ->get();
    

Pagination


$users = User::paginate(10);
    

Understanding Relationships

One of Eloquent’s strongest features is handling relationships.

One to One


// User.php
public function profile()
{
    return $this->hasOne(Profile::class);
}
    

One to Many


// User.php
public function posts()
{
    return $this->hasMany(Post::class);
}
    

Many to Many


// User.php
public function roles()
{
    return $this->belongsToMany(Role::class);
}
    

Polymorphic


// Comment.php
public function commentable()
{
    return $this->morphTo();
}
    

Loading Related Data

Use with() for eager loading:


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

Mutators and Accessors

You can format attributes automatically with accessors and mutators.


class User extends Model
{
    // Accessor
    public function getNameAttribute($value)
    {
        return ucfirst($value);
    }

    // Mutator
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }
}
    

Scopes

Define reusable query logic with scopes.


class User extends Model
{
    public function scopeActive($query)
    {
        return $query->where('is_active', 1);
    }
}

// Usage
$users = User::active()->get();
    

Soft Deletes

Instead of permanently deleting records, Eloquent can mark them as deleted.


use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;
}
    

Now, deleted_at will be set instead of actually deleting the record.

Best Practices for Using Eloquent

  • Use mass assignment with $fillable or $guarded.
  • Eager load relationships to reduce N+1 queries.
  • Use scopes for reusable query logic.
  • Leverage accessors and mutators for clean data handling.
  • Keep models slim; use repositories or services for business logic.

Conclusion

Laravel’s Eloquent ORM transforms the way you interact with databases. With its expressive syntax, built-in relationships, and powerful query builder, it allows you to write clean, maintainable, and scalable database interactions.

By mastering Eloquent basics—models, CRUD operations, relationships, scopes, and more—you’ve taken a giant leap in becoming a proficient Laravel developer. The journey doesn’t stop here. Explore advanced features like custom collections, query caching, and performance optimization to unlock Eloquent’s full power.

This website uses cookies to enhance your browsing experience. By continuing to use this site, you consent to the use of cookies. Please review our Privacy Policy for more information on how we handle your data. Cookie Policy