Introduction to Eloquent in Laravel
Introduction to Eloquent in Laravel
Eloquent is Laravel's built-in Object-Relational Mapper (ORM), designed to make database interactions easy, intuitive, and more aligned with object-oriented programming principles. With Eloquent, database records are treated as objects, and developers can interact with the database using Laravel’s built-in methods instead of writing raw SQL queries. This makes Eloquent an essential part of Laravel, especially for projects that need to manage data across tables.
Key Concepts of Eloquent:
Models: Eloquent models are used to interact with database tables. Each model corresponds to a specific table in the database, allowing you to perform queries and other operations on the table using the model.
- Example: A
User
model corresponds to ausers
table.
class User extends Model {}
- Example: A
Active Record Implementation: Eloquent follows the Active Record pattern, where each model is tied directly to the database, and an instance of the model represents a row in the database table.
Example: A single record from the
users
table can be accessed like so:$user = User::find(1); // Finds the user with id 1
CRUD Operations: Eloquent simplifies Create, Read, Update, and Delete (CRUD) operations. You can perform these actions without writing raw SQL queries:
Create:
$user = new User(); $user->name = 'John Doe'; $user->email = 'john@example.com'; $user->save();
Read:
$user = User::find(1); // Retrieve user with id 1 $users = User::all(); // Retrieve all users
Update:
$user = User::find(1); $user->name = 'Jane Doe'; $user->save();
Delete:
$user = User::find(1); $user->delete();
Query Builder Integration: Eloquent uses Laravel's Query Builder to provide a fluent interface for building complex queries. It can perform filtering, sorting, and joins through expressive methods.
- Example: Fetch all users with the name 'John Doe':
$users = User::where('name', 'John Doe')->get();
- Example: Fetch all users with the name 'John Doe':
Relationships: Eloquent supports defining relationships between models, allowing you to represent associations like one-to-many, many-to-many, and more.
One-to-Many Relationship (e.g., a post has many comments):
class Post extends Model { public function comments() { return $this->hasMany(Comment::class); } }
Belongs-to Relationship (e.g., a comment belongs to a post):
class Comment extends Model { public function post() { return $this->belongsTo(Post::class); } }
Timestamps: Eloquent automatically manages
created_at
andupdated_at
timestamps on your models. You can disable this feature if not needed.public $timestamps = false;
Mass Assignment: Eloquent allows mass assignment of attributes by specifying which fields can be filled all at once using an array. The
$fillable
property defines which fields are allowed to be mass-assigned.protected $fillable = ['name', 'email', 'password'];
Eager Loading: Eloquent can eager-load relationships to avoid the "N+1" query problem. This fetches related models in a single query, improving performance.
- Example:
$posts = Post::with('comments')->get(); // Fetch all posts and their comments
- Example:
Example Use Case:
Suppose you have two tables: posts
and comments
. You can define models Post
and Comment
to represent these tables and define their relationship like this:
class Post extends Model {
public function comments() {
return $this->hasMany(Comment::class);
}
}
class Comment extends Model {
public function post() {
return $this->belongsTo(Post::class);
}
}
Now, you can easily fetch a post and all its related comments like so:
$post = Post::with('comments')->find(1); // Fetch post with id 1 and its comments