While I can't provide specific lesson titles from Laracasts, I can certainly explain how Laravel's Form Request works and how you can use it in your projects.
What is a Form Request?
A Form Request in Laravel is a custom request class that encapsulates validation logic. It helps keep your controller methods clean and focused by moving validation logic into a separate class.
How to Create a Form Request
You can create a Form Request using the Artisan command:
php artisan make:request StoreUserRequest
This command will generate a new request class in the app/Http/Requests directory.
Using the Form Request
Here's how you can use the Form Request in a controller:
-
Define Validation Rules:
Open the generated
StoreUserRequestclass and define your validation rules in therulesmethod:public function rules() { return [ 'name' => 'required|string|max:255', 'email' => 'required|email|unique:users,email', 'password' => 'required|string|min:8|confirmed', ]; } -
Authorize the Request:
You can also authorize the request in the
authorizemethod. Returntrueif the user is authorized to make this request:public function authorize() { return true; } -
Inject the Form Request into a Controller Method:
In your controller, type-hint the Form Request class in the method where you want to handle the form submission:
use App\Http\Requests\StoreUserRequest; class UserController extends Controller { public function store(StoreUserRequest $request) { // The incoming request is valid... // Retrieve the validated input data... $validated = $request->validated(); // Use the validated data to create a new user... User::create($validated); return redirect()->route('users.index'); } }
Benefits of Using Form Requests
- Separation of Concerns: Keeps your controller methods clean by moving validation logic to a separate class.
- Reusability: You can reuse the same Form Request class in multiple places if needed.
- Custom Validation Logic: You can add custom validation logic or messages within the Form Request class.
For more detailed lessons, you might want to check out the Laravel series on Laracasts, as they often cover topics like Form Requests in depth.