Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Laravel validation errors in react component which is in Laravel blade

I'm new to React. I'm using react form component partially in the Laravel blade. Then how can I send validation error messages from controllers to that react component which is resides in the Laravel blade file.

In my Controller,

public function store(Request $request)
{
    $rules = [
      'name' => 'required',
      'publish_at' => 'required|datetime'
    ];

    $this->validate($request, $rules);

    $book = Book::create([
        'name' => $request->name,
        'publish_at' => $request->publish_at
    ]);

    return response()->json($book);
}

In my laravel blade,

 <form method="POST" action="patients">
     @csrf
     <div class="form-group">
         <label for="name">Name</label>
         <input type="text" name="name" class="form-control" placeholder=". . .">
         @error('name')
         <span class="text-danger">{{ $message }}</span>
         @enderror
     </div>

     <div id="publish_at"></div> <!-- this is react component -->

     <button type="submit">Submit</button>
</form>
like image 337
Siri Avatar asked Nov 06 '22 11:11

Siri


1 Answers

According to Laravel docs, they send a response with 422 code on failed validation:

If the incoming request was an AJAX request, no redirect will be generated. Instead, an HTTP response with a 422 status code will be returned to the browser containing a JSON representation of the validation errors

*So, you just need to handle response and, if validation failed, add a
validation message to the state, something like in the following code
snippet*


  request = $.ajax({ 
              url: "/user", 
              type: "post", 
              data: 'email=' + email + '&_token={{ csrf_token() }}',
              data: {'email': email, '_token': $('meta[name=_token]').attr('content')},
              beforeSend: function(data){console.log(data);},
              error: function(jqXhr, json, errorThrown) {
                if(jqXhr.status === 422) {
                    //status means that this is a validation error, now we need to get messages from JSON
                    var errors = jqXhr.responseJSON;
                    var theMessageFromRequest = errors['email'].join('. ');
                    this.setState({
                        validationErrorMessage: theMessageFromRequest,
                        submitted: false
                    });
                }
              }.bind(this)
        });

After that, in the 'render' method, just check if this.state.validationErrorMessage is set and render the message somewhere:

render: function() {
    var text = this.state.submitted ? 'Thank you!  Expect a follow up at '+email+' soon!' : 'Enter your email to request early access:';
    var style = this.state.submitted ? {"backgroundColor": "rgba(26, 188, 156, 0.4)"} : {};
    return (
      <div>
        {this.state.submitted ? null :
            <div className="overall-input">
              <ReactCSSTransitionGroup transitionName="example" transitionAppear={true}>
                  <input type="email" className="input_field" onChange={this._updateInputValue} ref="email" value={this.state.email} />
                  <div className="validation-message">{this.state.validationErrorMessage}</div>
                  <div className="button-row">
                      <a href="#" className="button" onClick={this.saveAndContinue}>Request Invite</a>
                  </div> 
              </ReactCSSTransitionGroup>
            </div>                            
        }
      </div>
    )
  }
like image 167
sss S Avatar answered Nov 15 '22 06:11

sss S