Laravel for Beginners: Form Requests and Validation Rules

Arlind Musliu Portrait

Arlind Musliu

January 15, 2024 · 3 min read · 13 views

Laravel Blogpost Image

In the journey of building an app with Laravel, form requests are your safeguard, ensuring that the content your users contribute is in pair with the standards you've set. Laravel's validation rules enforce these standards, guarding against invalid data.

We will combine the concept of form requests with some common validation rules to illustrate how you can maintain the quality and integrity of your blog's content.

Creating a Form Request

Let's start by creating a form request for storing blog posts. This request will ensure that the posts meet our criteria before they're saved to the database.

php artisan make:request StorePostRequest

This command generates a StorePostRequest class in the app/Http/Requests directory.

Defining Validation Rules in the Form Request

In our StorePostRequest class, we'll define a set of rules in the rules method to validate the new blog posts:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StorePostRequest extends FormRequest
{
    public function authorize()
    {
        // Only allow logged-in users to create a blog post
        return auth()->check();
    }

    public function rules()
    {
        return [
            'title' => 'required|max:255|unique:posts',
            'content' => 'required|min:100',
            'image' => 'nullable|image|max:2048',
            'tags' => 'array',
            'tags.*' => 'exists:tags,id'
        ];
    }
}

Let's break down these validation rules:

  • 'title' => 'required|max:255|unique:posts' ensures that the title field is not empty, it does not exceed 255 characters, and it's unique in the posts table.

  • 'content' => 'required|min:100' checks that the content is present and is at least 100 characters long, ensuring meaningful blog posts.

  • 'image' => 'nullable|image|max:2048' allows an optional image upload, verifies that the file is indeed an image, and restricts its size to 2MB.

  • 'tags' => 'array' ensures that the tags input is an array, which is useful when selecting multiple tags for a post.

  • 'tags.*' => 'exists:tags,id' checks each item in the tags array to ensure it corresponds to an existing tag ID in the tags table.

Using the Form Request in a Controller

Now that we've set up our StorePostRequest, we can use it in our PostController:

<?php 

namespace App\Http\Controllers;

use App\Http\Requests\StorePostRequest;
use App\Models\Post;

class PostController extends Controller
{
	// other methods

    public function store(StorePostRequest $request)
    {
        // The validated data is automatically retrieved
        $validatedData = $request->validated();
        
        // Create and save the new post with the validated data
        $post = Post::create($validatedData);
        
        // Attach tags if provided
        if ($request->has('tags')) {
            $post->tags()->sync($request->tags);
        }
        
        // Redirect to the new post with a success message
        return redirect()->route('posts.show', $post)
						 ->with('success', 'Post created successfully!');
    }
}

Conclusion

Form requests and validation rules in Laravel work together to provide a robust system for handling user input. By using these tools, you can ensure that every blog post on your site meets your standards for quality and consistency. The rules help prevent common issues like duplicate titles or insufficient content, while the form requests keep your controller methods clean and focused on their core responsibilities.

Upcoming Articles in the Series

  1. Laravel for Beginners: Task Scheduling for Automation

  2. Laravel for Beginners: Error Handling

  3. Laravel for Beginners: Using Queues


Bring Your Ideas to Life 🚀

If you need help with a Laravel project let's get in touch.

Lucky Media is proud to be recognized as a Top Laravel Development Agency

Arlind Musliu Portrait
Arlind Musliu

Cofounder and CFO of Lucky Media

Technologies:

Heading Pattern

Related Posts

Stay up to date

Be updated with all news, products and tips we share!