Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

stevenmusumeche's avatar

Form request image validation differences between 5.1 and 5.2

I'm in the process of upgrading an app from Laravel 5.1 to 5.2. The application is an API and one of the endpoints accepts an image upload named 'avatar'. In Laravel 5.1, the following validation rule works:

    public function rules()
    {
        return [
            'avatar' => 'required|image'
        ];
    }

However, in 5.2, I get the error 'Avatar must be an image'. When dumping $request->avatar, I can see that it is an instance of Illuminate\Http\UploadedFile as expected.

Any ideas?

0 likes
5 replies
AlexYa's avatar

Did you check your form and if there is enabled enctype="multipart/form-data" or file=> true in Html Form package ?

stevenmusumeche's avatar

Yes, I did verify both of those things. The same issue happens when using mimetypes. Here is what the failing UploadedFile looks like:

Illuminate\Http\UploadedFile {#779
  -test: false
  -originalName: "cn.png"
  -mimeType: "image/png"
  -size: 10
  -error: 0
  path: "/var/www/conversations-api/storage/app"
  filename: "temp_avatar.png"
  basename: "temp_avatar.png"
  pathname: "/var/www/conversations-api/storage/app/temp_avatar.png"
  extension: "png"
  realPath: "/var/www/conversations-api/storage/app/temp_avatar.png"
  aTime: 2016-07-17 20:05:24
  mTime: 2016-07-17 20:05:38
  cTime: 2016-07-17 20:05:38
  inode: 1532
  size: 17245
  perms: 0100774
  owner: 33
  group: 33
  type: "file"
  writable: true
  readable: true
  executable: true
  file: true
  dir: false
  link: false
}
leandromatos's avatar

@stevenmusumeche You should use the rule mime type for file validation.

For example, to image files you would do something like:

public function rules()
{
    return [
        'avatar' => 'required|mimes:jpg,png'
    ];
}
stevenmusumeche's avatar
Level 2

For anyone else that has this problem, the issue was not in the validator at all. There is a bug in Laravel 5.2 from converting Symfony UploadedFile objects with the "test" attribute as true to Laravel's similar UploadedFile object. In my tests, I was uploading Symfony UploadedFile file objects with "test" = true. By changing these to Illuminate\Http\UploadedFile it works.

1 like

Please or to participate in this conversation.