Validate specific rule - Laravel

Asked by At

I am using latest Laravel version.

I have requests/StoreUser.php:

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

for creating a user.

Now I need and to update the user, but how can I execute only specific rules ?

For the example, if name is not provided, but only the email, how can I run the validation only for the email ?

3 Answers

2
Michael Nguyen On

This is easier than you thought. Make rules depend on the HTTP method. Here is my working example.

public function rules() {
    // rules for updating record
    if ($this->method() == 'PATCH') {
        return [
            'name' => 'nullable||max:255|min:2', // either nullable or remove this line is ok
            'email' => 'required|unique:users|email',
        ];
    } else {
    // rules for creating record
        return [
            'name' => 'required||max:255|min:2',
            'email' => 'required|unique:users|email',
            'password' => 'required|max:255|min:6|confirmed'
        ];
    }

}
1
MasteRus On

You can separate your StoreUser request to CreateUserRequest and UpdateUserRequest to apply different validation rules. I think, this separation makes your code more readable and understandable.

1
Omar Makled On

Any HttpValidation request in laravel extends FormRequest that extends Request so you always have the ability to check request, auth, session, etc ...

So you can inside rules function check request type

class AnyRequest extends FormRequest
{
    public function rules()
    {
        if ($this->method() == 'PUT'){
            return [

            ]
        }
        if ($this->method() == 'PATH') {
            return [

            ]
        }
    }
}

If things get complicated you can create a dedicated new HttpValidation request PostRequest PatchRequest

class UserController extends Controller
{
    public function create(CreateRequest $request)
    {

    }

    public function update(UpdateRequest $request)
    {

    }
}

See also the Laravel docs: