transaction_type == 'SELL') { $average_cost_basis = Transaction::where([ 'portfolio_id' => $model->portfolio_id, 'symbol' => $model->symbol, 'transaction_type' => 'BUY', ])->whereDate('date', '<=', $model->date) ->average('cost_basis'); $model->cost_basis = $average_cost_basis ?? 0; } return $next($model); } }