Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

borrie's avatar

Default value if field is empty

Hi there. I'm creating an admin panel for one of our e-commerce stores. The goal is to let the user create a discount code. If the field is left empty I want to create a random string for it.

 /**
     * Get the fields displayed by the resource.
     *
     * @param  \Laravel\Nova\Http\Requests\NovaRequest  $request
     * @return array
     */
    public function fields(NovaRequest $request)
    {
        return [
            ID::make()->sortable()->hideFromIndex(),
            Text::make('Coupon', 'coupon')->placeholder('Leave empty to generate automatic'),
            Select::make('Type')->options([
                'percentage' => 'Percentage',
                'fixed' => 'Fixed amount',
            ]),
            Number::make('Amount', 'amount'),
        ];
    }

I'm not sure how to approach this. I was thinking to create an observer for it and see if the field is left empty and then fill it with a random string. Does anyone know if there is a more easier way to solve this problem?

0 likes
1 reply
borrie's avatar

The observer:

class DiscountObserver
{
    /**
     * Handle the "Discount" created event.
     *
     * @param Discount $discount
     * @return void
     */
    public function created(Discount $discount)
    {
        if (is_null($discount->coupon)) {
            $discount->coupon = strtoupper(Str::random(16));
            $discount->save();
        }
    }
}

Please or to participate in this conversation.