0

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 ?

2
  • 1
    Use the sometimes validation rule. But I'm not sure it works with required. laravel.com/docs/5.8/validation#conditionally-adding-rules Commented Apr 20, 2019 at 23:28
  • 1
    When you retrieve the rule of arrays, simply remove the key that you don’t want to validate. array_forget($array, 'key_to_forget'); Commented Apr 20, 2019 at 23:30

3 Answers 3

2

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'
        ];
    }

}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.