Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

IvanPujianto's avatar

Lesson about Laravel's Form Request

Hi guys, is there any lesson that explaining about Laravel's Form Request in laracast ? may be a part of a series ?

Thank you for ur help.

0 likes
3 replies
LaryAI's avatar
Level 58

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:

  1. Define Validation Rules:

    Open the generated StoreUserRequest class and define your validation rules in the rules method:

    public function rules()
    {
        return [
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|string|min:8|confirmed',
        ];
    }
    
  2. Authorize the Request:

    You can also authorize the request in the authorize method. Return true if the user is authorized to make this request:

    public function authorize()
    {
        return true;
    }
    
  3. 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.

1 like

Please or to participate in this conversation.