5

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>
1
  • Kindly provide some code so that we can try to understand the situation better. Commented Nov 30, 2019 at 7:54

1 Answer 1

1

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>
    )
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.