In this post I will show you how to change your Laravel validation rules based on the request method type. This is useful when you want your validation logic encapsulated in one validation class. By the way. There’s nothing bad about having several classes, or doing validation in your controller methods.

Scenario

For this article we’ll focus on creating and updating a record. Let’s use the example of a blog post.

When creating a new blog post we want to ensure that the slug is unique in the posts table. We don’t want duplicate slugs in the database! When updating a post, we want to force the validator to ignore the rule for the post we’re updating.

Form Request Class

Make a new request called PostRequest by running the following artisan command.

php artisan make:request PostRequest

This will generate a file called PostRequest.php in app/Http/Requests.

Adding rules

The code example below defines several validation rules. For this article we’ll zone in on the rule for the slug only.

<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class PostRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title'     => 'required',
            'slug'      => 'required|unique:posts,slug',
            'content'   => 'required',
            'published' => 'required|boolean',
        ];
    }
}