422 name and mobile field required React js And Laravel 11. How to implement a form in React js that sends data to a Laravel backend?
To implement a form in React js that sends data to a Laravel backend, you can follow these steps:
- Set up a new Laravel project and create a route and controller for handling form submissions.
First, create a new Laravel project using the following command:
composer create --prefer-dist laravel/laravel project-name
Next, create a new route in routes/web.php
for handling form submissions:
Route::post('/submit-form', 'FormController@store');
Then, create a new controller called FormController.php
in the app/Http/Controllers
directory:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FormController extends Controller
{
public function store(Request $request)
{
// Process form data here
}
}
- Create a new React component for the form.
Create a new file called Form.js
in a new folder called components
:
import React, { Component } from 'react';
import axios from 'axios';
class Form extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
mobile: '',
errors: {}
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const { name, value } = event.target;
this.setState({ [name]: value });
}
handleSubmit(event) {
event.preventDefault();
axios.post('/submit-form', {
name: this.state.name,
mobile: this.state.mobile
})
.then(response => {
console.log(response.data);
this.setState({ name: '', mobile: '' });
})
.catch(error => {
this.setState({ errors: error.response.data.errors });
});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" name="name" value={this.state.name} onChange={this.handleChange} />
{this.state.errors.name && <span>{this.state.errors.name[0]}</span>}
</label>
<label>
Mobile:
<input type="number" name="mobile" value={this.state.mobile} onChange={this.handleChange} />
{this.state.errors.mobile && <span>{this.state.errors.mobile[0]}</span>}
</label>
<button type="submit">Submit</button>
</form>
);
}
}
export default Form;
- Use the form component in your React application.
Import the Form
component in your main App.js
file and use it in the JSX:
import React from 'react';
import Form from './components/Form';
function App() {
return (
<div className="App">
<Form />
</div>
);
}
export default App;
- Run the Laravel and React applications.
Start the Laravel development server by running php artisan serve
in the terminal.
Start the React development server by running npm start
in the React project directory.
Now, when you submit the form in the React application, the data will be sent to the Laravel backend and processed in the FormController@store
method.