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
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:
Convention
Description
Example
Table Names
Plural snake_case of the model name
Model: User → Table: users
Primary Key
By default named "id"
$table->id();
Timestamps
Eloquent 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();
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 article is a comprehensive tutorial on using the Prohibited Validation Rules in Laravel. You will learn how to apply prohibited, prohibited_if, and prohibited_unless with clear explanations, real-life scenarios, and code examples. This guide is perfect for developers who want to master advanced validation techniques in Laravel applications.
This detailed tutorial explores request validation in Laravel controllers. You’ll learn multiple techniques—basic controller validation, using form request classes, custom rules, conditional validation, error handling, localization, and best practices. With practical examples, code snippets, and structured explanations, this article is designed for beginners to advance learner.
This guide teaches you how to deploy Laravel applications to production servers. From preparing your environment and configuring Nginx or Apache, to database migrations, caching, performance optimization, CI/CD pipelines, and security practices—this article covers everything step by step.It’s suitable for both beginners and advanced developers who want to ship stable, secure & scalable app.
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
These cookies are essential for the website to function properly.
These cookies help us understand how visitors interact with the website.
These cookies are used to deliver personalized advertisements.