20 Laravel Eloquent Tips and Tricks (P1)

Eloquent ORM được sủ dụng rất nhiều trong 1 project Laravel, tuy nhiên để sử dụng được tối đa những gì Laravel cung cấp thì không phải ai cũng biết. Trong bài viết này mình sẽ chỉ cho các bạn một vài thủ thuật, hi vọng sẽ giúp ích cho các bạn trong một vài trường hợp cụ thể.

1. Increments và Decrements

Khi muốn update tăng 1 đơn vị cho 1 column thay vì viết như này.

$post = Post::find($postId);
$post->view_count++;
$post->save();

Bạn có thể viết lại như này

$post = Post::find($postId);
$post->increment('view_count');

Hoặc

Post::find($postId)->increment('view_count');
Post::find($postId)->increment('view_count', 10); // +10
Product::find($productId)->decrement('stock'); // -1

2. XorY methods

Laravel Eloquent có khả nhiều function kết hợp 2 methods kiểu như “hãy làm X trước nếu không thì làm Y”

  • findOrFail
$user = User::find($id);
if (!$user) {
   abort(404);
}

$user = User::findOrFail($id);
  • firstOrCreate
$user = User::where('email', $email)->first();
  if (!$user) {
  User::create([
  'email' => $email
  ]);
}

$user = User::firstOrCreate(['email' => $email]);

3. Model boot() method

Trong Laravel Eloquent có một function boot() cho phép bạn ghi đè lại các giá trị mặc định.

class User extends Model
{
    /**
    * @return void
    */
    public static function boot(): void
    {
        parent::boot();
        static::updating(function($model)
        {
            // do some logging
            // thay thế một số property, ví dụ $model->something = transform($something);
        });
    }
}

Ứng dụng nhiều nhất của function này là set uuid cho đối tượng

/**
* @return void
*/
public static function boot(): void
{
    parent::boot();
    self::creating(function ($model) {
        $model->uuid = (string)Uuid::generate();
    });
}

4. Thêm điều kiện hoặc ordering trong relationship

Dưới đây là một cách mà các bạn thường dùng để định nghĩa một relationship

/**
* @return mixed
*/
public function users()
{
    return $this->hasMany('App\User');    
}

Tuy nhiên bạn hoàn toàn có thể thêm where hoặc orderBy

Ví dụ trong trường hợp cụ thể, bạn cần tạo quan hệ giữa bảng categories và posts nhưng thêm điều kiện là post phải có trạng thái là APPROVED và sắp xếp theo thứ tụ tăng dần.

/**
* @return mixed
*/
public function posts() 
{
    return $this->hasMany('App\Models\Category')->where('status', 'APPROVED')->orderBy('id', 'DESC');
}

5. Model properties: timestamps, appends, …

Có một vài parameters của Eloquent Model, được thể hiện dưới dạng properties của class đó. Một số cái phổ biến nhất có thể là:

class User extends Model {
    protected $table = 'users';
    protected $fillable = ['email', 'password']; // Những fileds có thể được set giá trị bằng cách dùng User::create()
    protected $dates = ['created_at', 'deleted_at']; // Những fields sẽ được set bởi Carbon-ized
    protected $appends = ['field1', 'field2']; // Các giá trị bổ sung được trả về trong JSON 
}

Khoannnnnnnnnnnnnnnnnnn, Còn nữa…

protected $primaryKey = 'uuid'; // Primary key k phải lúc nào cũng bắt buộc phải là id
public $incrementing = false; // và thậm chí k cần phải tự động tăng luông 
protected $perPage = 25; // Bạn có thể override số lượng data trong 1 page khi sủ dụng pagination, giá trị này default là 15
const CREATED_AT = 'created_at';
const UPDATED_AT = 'updated_at'; // Thay đổi được tên column created_at và updated_at luôn nè 
public $timestamps = false; // Hoặc khai báo là k cần sủ dụng chúng
protected $dateFormat = 'U'; //Hoặc bạn có thể thay đổi kiểu dữ liệu của chúng. Ví dụ chuyển created_at và updated_at sang integer thì làm như ví dụ này.

Và tất nhiên là còn nhiều hơn nữa, trên đây mình đã liệt kê những cái thú vị nhất, để biết thêm chi tiết, vui lòng kiểm tra ở abstract Model Class

To be continued…

0 Shares:
1 comment
Leave a Reply

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

You May Also Like
Read More

SOLID Principles

Table of Contents Hide Single-responsibility PrincipleOpen/Closed Principle (OCP)Liskov Substitution Principle (LSP)Interface Segregation Principle (ISP)Dependency Inversion Principle (DIP)Advantages of…