To achieve the desired functionality in Laravel Nova, you can use the dependsOn method to dynamically update the cost_per_order field based on the selected OrderType. Here's how you can implement this:
-
Use the
dependsOnmethod to listen for changes in theorderTypefield. -
Fetch the
current_costfrom the selectedOrderTypeand set it as the value forcost_per_order.
Here's how you can modify your code:
use Laravel\Nova\Fields\BelongsTo;
use Laravel\Nova\Fields\Number;
use Laravel\Nova\Http\Requests\NovaRequest;
use Laravel\Nova\Fields\FormData;
public function fields(Request $request)
{
return [
BelongsTo::make('Order Type', 'orderType', OrderType::class),
Number::make('Cost per Order', 'cost_per_order')
->dependsOn(
['orderType'],
function (Number $field, NovaRequest $request, FormData $data) {
if ($data->orderType === null) {
$field->hide();
} else {
// Fetch the OrderType model
$orderType = \App\Models\OrderType::find($data->orderType);
if ($orderType) {
// Set the value of cost_per_order to current_cost of the selected OrderType
$field->value = $orderType->current_cost;
}
}
}
),
];
}
Explanation:
-
BelongsTo Field: This field is used to select the
OrderType. It is linked to theOrderTypemodel. -
Number Field: The
cost_per_orderfield is a number field that depends on theorderTypefield. -
dependsOn Callback: Inside the callback function, we check if
orderTypeis not null. If it's not null, we fetch theOrderTypemodel using the ID from$data->orderType. -
Set Value: If the
OrderTypeis found, we set thevalueof thecost_per_orderfield to thecurrent_costof the selectedOrderType.
This setup will ensure that the cost_per_order field is hidden until an OrderType is selected, and once selected, it will automatically populate with the current_cost from the OrderType.