laravelvalidation

Laravel request validation - nullable image


I have registration form with username, email, password and avatar(image) fields. Everything works except image filed, which can be null. I am using Vue as front-end and send data with axios to Laravel.

This is validation:

public function register(Request $request)
{
    $request->validate([
        'username' => 'required|string|max:255|unique:users',
        'email' => 'required|string|email|max:255|unique:users',
        'password' => 'required|string|min:6',
        'avatar' => 'nullable|image|mimes:jpg,jpeg,png|max:1999'
    ]);

    $fileNameToStore = 'noimage.jpg';

    return User::create([
        'username' => $request->username,
        'email' => $request->email,
        'password' => Hash::make($request->password),
        'avatar' => $fileNameToStore
    ]);
}

And this is how I send data:

register(context, data) {
      let formData = new FormData();
      formData.append('avatar', data.avatar)
      formData.append('username', data.username)
      formData.append('email', data.email)
      formData.append('password', data.password)

      return new Promise((resolve, reject) => {
        axios.post('/register', formData,{
          headers: {
              'Content-Type': 'multipart/form-data'
          }
        })
          .then(response => {
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
}

If I fill out every filed it works fine and also other things like checking extension or file size works, only problem is when I don't select any image. I have nullable included in validation, but I still get error message from validation that it must be an image and which extension it needs to have.


Solution

  • If your data.avatar is undefined or null, your server will eiter receive a undefined or null string as a value for your avatar field. Therefore, Laravel will be testing the image rule on the string.

    To fix it, you can make sure your image is not undefined to send it in your request.

    if (data.avatar) {
        formData.append('avatar', data.avatar);
    }
    

    Or

    formData.append('avatar', data.avatar ?? '');