mr_kiani
mr_kiani

Reputation: 43

I am getting a null in database fields

The following code is in view :

    <input maxlength="2" value="{{ old('discount') }}" 
     class="form-control" type="text" 
     id="product-discount-in-adding-products" 
     name="discount">

and this is my code in controller:

if($request->has('discount')){
    $product->discount = $request->discount;
}else{
    $product->discount = 0;
}

when I send a form by post my discount fields in a database will give a null.

Upvotes: 1

Views: 70

Answers (1)

Jonathon
Jonathon

Reputation: 16333

In Laravel 5.5, the has method on the request object tells you only if the field is actually present in the request, not whether or not it has a value. So if you submit an empty value in your form for discount, your first check if($request->has('discount')){ will be true.

Now, Laravel also has middlewares to trim strings and convert empty strings to null so if you're submitting an empty value in your discount field, then you will be setting $product->discount to null.

The way to check if form contains a value for the specified input, is to use the filled method instead:

if ($request->filled('discount')) {
    $product->discount = $request->discount;
} else {
    $product->discount = 0;
}

This should stop the first check evaluating to true and will set $product->discount to 0.

See the documentation here under the heading labelled Determining If An Input Value Is Present.

Upvotes: 3

Related Questions