0
votes

I have used front end is Angular and backend is Laravel, Create user call store function, it triggers to validate the user request using "UserRequest".

All validation working perfectly.

Now I will update the user record based on the field value change, not all fields.

The UserController update function triggers while updates the record, but not all fields I passed to update. one specific field.

Example:

The requests pass "Age=40" to the only update. but UserRequest validates all the fields and throw the error required fields. How to I use reuse the request also achieve the output.

// UserController
public function store(UserRequest $request)
{
   //TODO...
}

and

// UserRequest
public function rules()
    {
        return [
            'name' => 'required',
            'email' => 'required|email',
            'age' => 'required|integer|min:15',
        ];
    }

and

// UserController
public function Update(UserRequest $request, User $user)
{
   //TODO...
   $user->update($request->all());
}
1

1 Answers

1
votes

Add sometimes to your rules

public function rules()
    {
        return [
            'name' => 'sometimes|required',
            'email' => 'sometimes|required|email',
            'age' => 'sometimes|required|integer|min:15',
        ];
    }

This will only validate if the data is present see more https://laravel.com/docs/5.4/validation#conditionally-adding-rules