Back to Blog
3 min read

Level Up Your Laravel Forms with Request Validation

LaravelProgrammingWeb DevelopmentTutorial

Laravel provides a robust and elegant way to handle form data validation. Instead of scattering validation logic throughout your controllers, you can leverage Request objects to keep your code clean and maintainable. Let's dive into some practical examples. 1. Creating a Request Class: First, let's generate a dedicated Request class using Artisan:

php artisan make:request StorePostRequest

This command will create a new file at app/Http/Requests/StorePostRequest.php. Inside this file, you'll define your validation rules:

<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StorePostRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true; // Or your authorization logic here
    }
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array|string>
     */
    public function rules(): array
    {
        return [
            'title' => 'required|string|max:255',
            'content' => 'required|string',
            'category_id' => 'required|integer|exists:categories,id',
        ];
    }
}

Explanation:

  • authorize(): Determines if the user is allowed to perform this request. You can add your authorization logic here. For simple cases, setting it to true works fine.
  • rules(): Defines the validation rules. In this example, the title is required, a string, and has a maximum length. The content is required and a string, and category_id is required, an integer, and must exist in the categories table with the id column. 2. Using the Request Class in Your Controller: Now, inject your custom Request class into your controller method. Laravel will automatically perform the validation, and if it fails, it will redirect the user back to the form with error messages.
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StorePostRequest;
use App\Models\Post;
class PostController extends Controller
{
    public function store(StorePostRequest $request)
    {
         // If validation passes, you can access the validated data using $request->validated()
        $validatedData = $request->validated();
        Post::create($validatedData);
        return redirect()->route('posts.index')->with('success', 'Post created successfully!');
    }
}

Explanation:

  • We are type-hinting StorePostRequest in the store method. Laravel's service container automatically resolves this dependency.
  • If validation passes, the controller code proceeds as usual.
  • $request->validated() provides an array of the validated data, which is safe to use. 3. Customizing Error Messages: To provide user-friendly error messages, you can customize them in the messages method within your Request class:
public function messages()
{
    return [
        'title.required' => 'The post title is mandatory.',
        'title.max' => 'The title cannot be longer than 255 characters.',
        'content.required' => 'Please provide the content of the post.',
        'category_id.required' => 'Please select a category for this post.',
        'category_id.integer' => 'Invalid category selected.',
        'category_id.exists' => 'The selected category does not exist.',
    ];
}

4. Best Practices:

  • Keep your controllers clean: By using Request classes, you're separating concerns and making your controller logic much easier to read and maintain.
  • Use meaningful rules: Choose appropriate validation rules based on your data's requirements.
  • Provide clear error messages: Guide users to correct errors with well-defined and understandable messages.
  • Leverage Laravel's powerful validation rules: Explore the vast array of available rules to cover various validation scenarios. By using Laravel Request validation effectively, you'll build more robust, maintainable, and user-friendly applications. Tags: #Laravel #Validation #Forms #PHP

Share this post