0

i have an checkbox in my blade where users can enable an other Payment method and now i want if someone check this box, the price is required for this Payment method.

Checkbox Blade

<div class="form-group">
    <label for="accept1">
        <img src="/img/accept1.png">
        Accept other payment method
    </label>
    <input type="checkbox" value="true" name="accept1"> Yes
</div>

Price Blade

<div class="form-group">
    <label for="newprice"><img src="/img/newprice.png"> New</label>
    <input type="number" step="any" name="newprice" value="{{old('newprice')}}">
</div>

Controller

<?php

if ($request->accept1 == 'true') {
    $product->accept1 = true;
}

if ($request->newprice == 'true') {
    if (!is_numeric($request->newprice) || $request->newprice <= 0.0001) {
        session()->flash('errormessage', ' Price is required');
        return redirect()->back()->withInput();
    }
}

If someone clicks the checkbox now, they must also enter a price or they get an error message.

How can I change the code to make it work?

Karl Hill
  • 12,937
  • 5
  • 58
  • 95
pirson343
  • 11
  • 1
  • Possible duplicate of [Laravel blade check box](https://stackoverflow.com/questions/26973442/laravel-blade-check-box) – Adam Kozlowski Jan 30 '18 at 13:02
  • Thats dont help me.. – pirson343 Jan 30 '18 at 13:07
  • The Laravel documentation has a [huge section on validation](https://laravel.com/docs/5.5/validation) - I highly recommend having a look at the code examples there because it looks like you're not even leveraging its powerfule and extremely convenient request validation and input error handling. What you're looking for is the `required_if` validation rule. – Quasdunk Jan 30 '18 at 13:21

3 Answers3

0

You can use Laravel Form validation to do this.

From the docs:

required_if:anotherfield,value,...

The field under validaYou can use Laravel Form validation to do this:tion must be present and not empty if the another field field is equal to any value.

Try:

$request->validate([
    'newprice' =>  'required_if:accept1,==,true',
]);
Sapnesh Naik
  • 11,011
  • 7
  • 63
  • 98
0

You can use laravel validation rule like below:

$validator = Validator::make($request->all(), [
        "newprice" =>"required_if:accept1,==,true|numeric|min:0.0001"
    ]); 


if ($validator->fails()) {
        return redirect()->back()
                    ->withErrors($validator)
                    ->withInput();
    }

https://laravel.com/docs/5.5/validation

0

Try below Code:

  If($request->accept1 === true){

            Validator::make($request->all(), [
                   "newprice" =>"required"
                  ],["newprice.required"=>"message"]);
     }
Boghani Chirag
  • 217
  • 1
  • 8