programing

웅변 모델 이벤트에서 이전 속성 값 가져오기

nicegoodjob 2023. 1. 16. 21:10
반응형

웅변 모델 이벤트에서 이전 속성 값 가져오기

모델 속성의 이전/이전 값을 확인할 수 있는 방법이 있습니까?saving또는updating이벤트?

예: 다음과 같은 것이 가능합니까?

User::updating(function($user)
{
    if ($user->username != $user->old->username) doSomething();
});

네, 우연히 발견했어요. 현재 문서에는 없어요.

이 있습니다.getOriginal()원래 속성 값의 배열을 반환하는 메서드를 사용할 수 있습니다.

User::updating(function($user)
{
    if ($user->username != $user->getOriginal('username')) {
        doSomething();
    }

    // If you need multiple attributes you may use:
    // $originalAttributes = $user->getOriginal();
    // $originalUsername = $originalAttributes['username']; 
});

라라벨 7 이전엔 조심해요getOriginal는 아트리뷰트 타입 캐스팅을 무시합니다.

Larabel 4.0 및 4.1에서는 isDirty() 메서드로 확인할 수 있습니다.

User::updating(function($user)
{
    if ($user->isDirty('username')){
        doSomething();
    }
});

메서드를 오버로드하여 부모 메서드를 호출할 수 있습니다.

언급URL : https://stackoverflow.com/questions/17367383/get-previous-attribute-value-in-eloquent-model-event

반응형