422 name and mobile field required React js And Laravel 11. How to implement this in a React application using Laravel backend?
To implement a requirement where the name and mobile number are mandatory fields in a React application with a Laravel backend, follow the steps below:
- Set up the Laravel backend:
First, ensure you have a Laravel project set up with the necessary routes and validation rules. Here's a brief overview of how to create a simple form with validation rules:
a. Create a new controller:
php artisan make:controller UserController
b. Define the store method in the UserController:
use App\Http\Requests;
use App\Http\Requests\StoreUserRequest;
use App\User;
public function store(StoreUserRequest $request)
{
$user = new User;
$user->name = $request->name;
$user->mobile = $request->mobile;
$user->save();
return response()->json($user);
}
c. Define the StoreUserRequest validation rule:
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|string|max:255',
'mobile' => 'required|numeric|digits:10',
];
}
}
d. Define the route in web.php:
Route::post('/api/users', 'UserController@store');
- Set up the React application:
First, install Axios to make HTTP requests from the React application:
npm install axios
Next, create a new component to handle the form submission:
npx create-react-app form-component --template typescript
cd form-component
Replace the contents of src/App.tsx with the following code:
import React, { useState } from 'react';
import axios from 'axios';
const FormComponent: React.FC = () => {
const [name, setName] = useState('');
const [mobile, setMobile] = useState('');
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
try {
const response = await axios.post('/api/users', { name, mobile });
console.log(response.data);
} catch (error) {
console.error(error.response.data.errors);
}
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
value={name}
onChange={(event) => setName(event.target.value)}
/>
<label htmlFor="mobile">Mobile:</label>
<input
type="number"
id="mobile"
value={mobile}
onChange={(event) => setMobile(event.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
};
export default FormComponent;
Finally, update the src/index.tsx file to render the FormComponent:
import React from 'react';
import ReactDOM from 'react-dom';
import FormComponent from './App';
ReactDOM.render(<FormComponent />, document.getElementById('root'));
Now, when you run the React application and submit the form without entering a name or mobile number, the Laravel backend will return a validation error, which will be displayed in the React application.