laravel function 에서 중복 sql 호출 방지하기 once helper 사용

Updated on

laravel function 에서 중복으로 사용되는 곳에서 여러번 sql가 호출되는 것을 방지하고 싶을때가 있다.

https://laravel-news.com/once-helper https://laravel.com/docs/11.x/helpers#method-once

이때 사용할 수 있는 helper 가 once 헬퍼 함수이다. 생각보다 좋다.

    public static function getExchangeNames(Exchange $exchange): array
    {
        return once(function () use ($exchange) {
            return self::where('exchange', $exchange)
                ->get()
                ->pluck('name')
                ->toArray();
        });
    }

$exchange 값을 다르게해서 function 을 호출 하면, sql 를 맞게 새로운 요청을 보낸다.

생각보다 유용하다.