How To Add Form Validation In The Request Controller In Laravel



how to add form validation in the request controller in laravel

Adding form validation in the request controller in Laravel involves a few key steps. Here’s a concise guide on how to do it:

 1. Create a Form Request

First, generate a Form Request class, which will handle the validation logic. Use the Artisan command:

php artisan make:request StorePostRequest

This command creates a new request class in the `app/Http/Requests` directory.

 2. Define Validation Rules

Open the newly created `StorePostRequest` class and define your validation rules in the `rules` method:

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StorePostRequest extends FormRequest
{
  public function authorize()
  {
      return true; // You can add your authorization logic here
  }

  public function rules()
  {
      return [
          'title' => 'required|max:255',
          'body' => 'required',
          'email' => 'required|email',
      ];
  }

  public function messages()
  {
     return [
         'title.required' => 'The title field is required.',
         'body.required' => 'The body field is required.',
         'email.required' => 'The email field is required.',
         'email.email' => 'Please provide a valid email address.',
     ];
  }
}

 3. Use Form Request in Controller

Inject the `StorePostRequest` into your controller action. Laravel automatically handles the validation and redirects back to the form with errors if validation fails.

Here’s an example of how to use it in a controller:

namespace App\Http\Controllers;

use App\Http\Requests\StorePostRequest;

class PostController extends Controller
{
    public function store(StorePostRequest $request)
    {
       // The incoming request is valid...
       // Retrieve the validated input data...
       $validated = $request->validated();

       // Proceed with storing the post or any other logic
       // Post::create($validated);

       return redirect()->route('posts.index')->with('success', 'Post created successfully.');
   }
}

4. Handling Validation Errors

By default, Laravel will redirect the user back to the previous location with the validation errors stored in the session. You can display these errors in your Blade template like so:

@if ($errors->any())
   <div class="alert alert-danger">
     <ul>
        @foreach ($errors->all() as $error)
         <li>{{ $error }}</li>
        @endforeach
    </ul>
  </div>
@endif

Summary

– Create a Form Request using `php artisan make:request`.
– Define validation rules and messages in the generated request class.
– Inject the Form Request into your controller method to handle the validation.
– Handle validation errors in your Blade template to provide user feedback.

This approach keeps your controller methods clean and your validation logic organized.


Leave a Reply

Your email address will not be published. Required fields are marked *