php-laravelHow do I use Laravel FormRequest to validate a form in PHP?
FormRequest is a powerful feature of Laravel that allows you to validate forms in a clean, concise way. Here's an example of how to use it to validate a form:
// Create a Form Request class
use Illuminate\Foundation\Http\FormRequest;
class FormValidationRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|min:3',
'email' => 'required|email',
];
}
}
// Create a controller
public function store(FormValidationRequest $request)
{
// The form has been validated, continue with normal logic
}
The code above creates a new FormRequest class called FormValidationRequest. This class contains two methods: authorize()
and rules()
. The authorize()
method returns true or false to indicate whether the user is authorized to make the request. The rules()
method contains an array of validation rules that will be used to validate the form.
In the controller, you can pass the FormValidationRequest object to the store method, which will automatically validate the form using the rules specified in the FormValidationRequest class. If the validation fails, an exception will be thrown and the user will be redirected back to the form with the errors.
Helpful links
More of Php Laravel
- How can I use the @yield directive in PHP Laravel?
- How can I get the current year in PHP Laravel?
- How can I use PHP Laravel to create a Wikipedia page?
- How can I use PHP, Laravel, and Vue together to create a web application?
- How do I configure Xdebug in the php.ini file for a Laravel project?
- How do I set up a Laravel project with XAMPP on a Windows machine?
- How do I use PHP Laravel Tinker to debug my code?
- How do I set the timezone in PHP Laravel?
- How can I use the PHP Zipstream library in a Laravel project?
- How do I set up a .gitlab-ci.yml file for a Laravel project using PHP?
See more codes...