카테고리 없음

collection 컬렉션 where, firstWhere (특정 키의 값이 하나라도 존재한다면)

Sein_ 2023. 11. 22. 13:56
728x90
$orders = GripOrder::whereNotNull('commission')
    ->where('order_id', $request->order_number)
    ->get();

$orders->each(function($order){
    if($order->billing_no){
        throw new Exception("이미 사용된 주문번호 입니다.");
    }
});

 

팀장님 피드백

: $orders->each 말고 where/firstwhere 같은 다른 컬렉션을 사용하셨어도 좋을거같아요

https://laravel.com/docs/10.x/collections#method-where

https://laravel.com/docs/10.x/collections#method-first-where

 

# where() : The where method filters the collection by a given key / value pair

# firstWhere() : The firstWhere method returns the first element in the collection with the given key / value pair

 

변경 코드

if($orders->firstWhere('billing_no')){
    throw new Exception("이미 사용된 주문번호 입니다.");
}