laravel-news.com/eloquent-tips-tricks
20 Laravel Eloquent Tips and Tricks
Eloquent ORM seems like a simple mechanism, but under the hood, there’s a lot of semi-hidden functions and less-known ways to achieve more with it. In this article, I will show you a few tricks.1. Increments and DecrementsInstead of this:$article = Artic
laravel-news.com
3. Momdel boot() method
Eloquent 모델을 기본행동을 재정의하는 곳을 'boot()'라 한다.
class User extends Model
{
public static function boot()
{
parent::boot();
static::updating(function($model)
{
// do some logging
// override some property like $model->something = transform($something);
});
}
}
아마도 가장 인기있는 예는 모델객체가 만들어질 때, 필드를 세팅하는 것이다.
다음과 같이 UUID필드를 초기화 할 있다.
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->uuid = (string)Uuid::generate();
});
'Code > PHP' 카테고리의 다른 글
Model all: columns (0) | 2021.03.03 |
---|---|
Request->All 보단 Request->expect, Request only 를 쓰자,. (0) | 2021.03.01 |
php 에서 array에서 골라서 쓰고 싶을 때 (0) | 2021.02.27 |
phpstorm의 Laravel모델에서도 인텔리전스를 하고 싶을 때. (0) | 2021.02.26 |
fputcsv을 쓸 때 유의 사항(엑셀에서 읽어올려고 할 때) (0) | 2021.02.25 |