0

I want to validate the request to my createUser function so I create custom request and add my rules then I want to validate the same request to my updateUser function but I want to remove the rule of "required" in a new function without create new custom request

my custom request

class userRequest extends FormRequest
{
/**
 * 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 [
      'name' => 'required|string|max:255',
      'email' => 'required|string|email|max:255|unique:users',
      'password' => 'required|string|min:6|confirmed',
      'priv' => 'required|integer',
    ];
}
protected function failedValidation(Validator $validator)
{
    $response = [
    'status' => 'failure',
    'status_code' => 400,
    'message' => 'Bad Request',
    'errors' => $validator->errors(),
];
    throw new HttpResponseException(response()->json($response, 400));
}

}

2 Answers2

1

you can first check route and modify the $rules array, I suggest to you try the following code:

public function rules()
{
    $rules = [
        'name' => 'string|max:255',
        'email' => 'string|email|max:255|unique:users',
        'password' => 'string|min:6|confirmed',
        'priv' => 'integer',
    ];

    if (request()->route() != route('createUserRouteName')) { // write route name of createUser method
        foreach ($rules as $key => $rule) {
            $rules[$key] = 'required|' . $rule;
        }
    }
    return $rules;
}

I hope be useful, Let me know if there is a problem.

Ramin eghbalian
  • 2,348
  • 1
  • 16
  • 36
0

You should have a different request validation for each method you want to use, you can read more here https://laravel.com/docs/7.x/validation

Eliecer
  • 81
  • 2