0
0
Laravelframework~30 mins

Form request classes in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Form Request Classes in Laravel
📖 Scenario: You are building a simple Laravel application where users can submit their contact information through a form. To keep your controller clean and validate the data properly, you will use Laravel's Form Request classes.
🎯 Goal: Create a Form Request class to validate user input for a contact form. The form should require a name (string, required), email (valid email, required), and message (string, required, minimum 10 characters).
📋 What You'll Learn
Create a Form Request class named ContactFormRequest
Add validation rules for name, email, and message
Authorize all users to make the request
Use the Form Request class in a controller method
💡 Why This Matters
🌍 Real World
Form Request classes help keep your Laravel controllers clean and your validation logic organized. This is common in real Laravel applications handling user input.
💼 Career
Understanding Form Request classes is essential for Laravel developers to write maintainable and secure web applications.
Progress0 / 4 steps
1
Create the Form Request class
Create a Form Request class named ContactFormRequest by running the artisan command php artisan make:request ContactFormRequest. Then, open the generated file and set the authorize method to return true.
Laravel
Need a hint?

Use the artisan command to generate the class. Then edit the authorize method to allow all users.

2
Add validation rules
In the ContactFormRequest class, add validation rules inside the rules method for name as required string, email as required and valid email, and message as required string with minimum 10 characters.
Laravel
Need a hint?

Use Laravel validation rule strings inside the rules method's returned array.

3
Use the Form Request in a controller
In a controller named ContactController, create a method submit that accepts a parameter of type ContactFormRequest. Inside the method, assign the validated data to a variable called $validated by calling $request->validated().
Laravel
Need a hint?

Type hint the ContactFormRequest in the controller method and call validated() on the request.

4
Complete the controller method
In the submit method of ContactController, add a return statement that returns a JSON response with the validated data under the key data using response()->json().
Laravel
Need a hint?

Use Laravel's response()->json() helper to return the validated data as JSON.