간과된 라라벨 기능 두 가지: `fresh()`와 속성 가시성

발행: (2025년 12월 13일 오후 08:32 GMT+9)
2 min read
원문: Dev.to

Source: Dev.to

fresh() 로 모델 다시 로드하기

Laravel의 fresh 메서드는 모델이나 전체 컬렉션을 데이터베이스에서 다시 로드하여 가장 최신 데이터를 사용하고 있음을 보장합니다.

관계 이름을 fresh에 전달하면 해당 관계도 모델과 함께 다시 로드됩니다.

use App\Models\User;

$users = User::has('comments', 1)->with('comments')->get();

// 첫 번째 댓글을 로컬에서 수정 (저장되지 않음)
$users->first()->comments->first()->body = 'Updated body';

// 데이터베이스에서 사용자와 댓글을 다시 로드
$users = $users->fresh('comments');

visiblehidden 로 직렬화 제어하기

Laravel은 모델을 배열이나 JSON으로 변환할 때 어떤 속성이 표시될지 제어하기 위해 visiblehidden 속성을 제공합니다.

이 속성들은 관계 이름도 받을 수 있어, 직렬화 과정에서 관계를 명시적으로 표시하거나 숨길 수 있습니다.

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    /**
     * 배열에 표시될 속성들.
     *
     * @var array
     */
    protected $visible = [
        'name',
        'email',
        'created_at',
        'comments', // 일대다 관계
    ];
}

https://github.com/digging-code-blog/community-tips

Back to Blog

관련 글

더 보기 »