Laravel
[Laravel] Soft Deleting
초오오이
2024. 12. 18. 23:06
1. Soft Deleting 이란?
- DB 데이터의 일시적 삭제. 실제로 삭제하지 않고 삭제된 것처럼 처리하는 기능이다.
- 일반적으로 deleted_at 컬럼에 삭제 일시를 업데이트 해서 사용한다.
2. Soft Deleting 기능 활성화
1. 마이그레이션에서 deleted_at 컬럼 추가
Schema::table('flights', function (Blueprint $table) {
$table->softDeletes();
});
위처럼 작성하고 마이그레이션을 실행하면 timestamp 타입의 nullable 컬럼이 생성된다.
2. 모델에서 SoftDeletes 트레이트 추가
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Flight extends Model
{
use SoftDeletes;
}
3. 사용 예시
soft deleting 실행
$user = User::find(1);
$user->delete(); // 실제로는 deleted_at 컬럼에 시간이 기록됨
soft deleting된 레코드 조회
// 해당 레코드가 소프트 삭제되었는지 확인
if ($flight->trashed()) {
// 해당 처리
}
// 소프트 삭제된 레코드를 포함하여 조회
$flights = Flight::withTrashed()
->where('account_id', 1)
->get();
// 소프트 삭제된 레코드만 조회
$flights = Flight::OnlyTrashed()
->get();
soft deleting된 레코드 복원
// 방법1
$contact->restore()
// 방법2
Contact::onlyTrashed()->where('vip', true)->restore();
soft deleting된 레코드 완전 삭제
$flight->forceDelete();