Laravel – Eloquent ORM Fundamentals

2 min read


https://www.itsolutionstuff.com/upload/one-to-many-relationships-laravel.png
https://i.sstatic.net/n5RAR.png
https://cdn-images.visual-paradigm.com/guide/data-modeling/what-is-erd/01-entity-relationship-diagram.png

Eloquent ORM là gì?

Eloquent là ORM (Object Relational Mapping) mặc định của Laravel.
Nó cho phép bạn thao tác database bằng model thay vì viết SQL thuần.

Ví dụ thay vì:

SELECT * FROM users WHERE active = 1;

Bạn có thể viết:

User::where('active', 1)->get();

Tài liệu chính thức:
https://laravel.com/docs/eloquent


1️⃣ Active Record Pattern trong Eloquent

Eloquent sử dụng Active Record pattern.

Mỗi model đại diện cho một bảng.

class User extends Model
{
    protected $table = 'users';
}

Model vừa:

  • Đại diện dữ liệu
  • Chứa logic truy vấn
  • Tương tác database

Ưu điểm:

  • Viết nhanh
  • Dễ đọc
  • Phù hợp CRUD

Nhược điểm:

  • Có thể dẫn đến fat model nếu không kiểm soát

2️⃣ Mass Assignment & Fillable

Một lỗi bảo mật phổ biến khi dùng Eloquent là mass assignment.

Ví dụ:

User::create($request->all());

Nếu không cấu hình:

protected $fillable = ['name', 'email', 'password'];

Bạn có thể vô tình cho phép user ghi đè field không mong muốn (ví dụ role).

Luôn định nghĩa $fillable hoặc $guarded.


3️⃣ Relationship trong Eloquent

Đây là phần mạnh nhất của Eloquent.

One to One

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

One to Many

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

Many to Many

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

Eloquent tự động suy luận foreign key nếu bạn đặt tên đúng convention.


4️⃣ Lazy Loading vs Eager Loading

Mặc định Eloquent dùng lazy loading.

$users = User::all();foreach ($users as $user) {
    echo $user->posts;
}

Đây có thể gây N+1 query.

Giải pháp:

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

Eager loading giúp giảm số lượng query và tăng performance đáng kể.


5️⃣ Query Builder vs Eloquent

Eloquent:

User::where('active', 1)->get();

Query Builder:

DB::table('users')->where('active', 1)->get();

Khi nào dùng Query Builder?

  • Query phức tạp
  • Aggregate nặng
  • Performance critical

Eloquent tiện lợi, nhưng abstraction luôn có cost.


6️⃣ Accessor & Mutator

Accessor giúp format dữ liệu khi truy xuất:

public function getFullNameAttribute()
{
    return $this->first_name . ' ' . $this->last_name;
}

Dùng:

$user->full_name;

Mutator giúp xử lý trước khi lưu:

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

7️⃣ Casting

Eloquent hỗ trợ casting tự động:

protected $casts = [
    'is_active' => 'boolean',
    'created_at' => 'datetime',
];

Giúp tránh bug type khi xử lý dữ liệu.


8️⃣ Khi nào không nên dùng Eloquent?

Không nên dùng khi:

  • Bulk insert lớn
  • Report query phức tạp
  • Query performance-critical

Khi đó, raw query hoặc query builder sẽ tối ưu hơn.


Kết luận

Eloquent giúp:

  • Viết code nhanh
  • Dễ đọc
  • Tăng tốc phát triển

Nhưng nếu không hiểu rõ:

  • Có thể gây N+1 query
  • Có thể tạo fat model
  • Có thể ảnh hưởng performance

Eloquent mạnh, nhưng cần dùng đúng cách.

Avatar photo

Leave a Reply

Your email address will not be published. Required fields are marked *