Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call javaScript function in blade template after errors count found in Laravel?

I have small laravel project and trying now on input validation using request. Below is my request file.

public function rules()
{
    return [
        'name' => 'required', 
        'genericname' => 'required'
    ];
}

public function messages()
{
  return  [
        'name.required' => 'Name required',
        'genericname.required' => 'Genericname required'
  ]; 
}

My blade template work as normal to show flash once errors found as below code.

@if ($errors->count() > 0)
    <div class="alert alert-warning alert-dismissible" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        {{ $errors->first() }}
    </div>
@endif

But my concern is that, Is it possible to call javascript instead if errors found. For example of my need

@if ($errors->count() > 0)
    {{ callJavaScriptAlertFunction() }}
@endif

Any advise or guidance would be greatly appreciated, Thanks.

like image 234
joenpc npcsolution Avatar asked Oct 19 '25 23:10

joenpc npcsolution


2 Answers

You can use blade templates inside javascript. So create a function on document load.

assume you uses jQuery.

<script>
    $(document).ready(
        if({{ $errors->count() > 0 }}) {
            // your code goes here.
        }
    )
</script>
like image 99
Tharaka Dilshan Avatar answered Oct 21 '25 12:10

Tharaka Dilshan


Something like this would work:

@if ($errors->count() > 0)
    <script>
        alert("Error: " + {{ $errors->first() }});
    </script>
@endif
like image 37
Syed Shoaib Abidi Avatar answered Oct 21 '25 12:10

Syed Shoaib Abidi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!