Black Friday: coupon FRIDAY24 for 40% off Yearly/Lifetime membership! Read more here

Four Laravel Validation Rules for Images and Photos

Laravel Validation mechanism has a lot of various rules. Let's pick the ones that can be applied to graphical files.

Rule 1. image

Probably the most straightforward one:

public function rules()
{
    return [
        'uploaded_photo' => 'image',
    ];
}

Probably, good question would be What is an image?

From the docs: The file under validation must be an image (jpeg, png, bmp, gif, or svg)


Rule 2. mimes

If the image extensions listed above is too many for you, you can limit them to specifically JPG/PNG, for example:

public function rules()
{
    return [
        'photo' => 'mimes:jpeg,png',
    ];
}

Even though you only need to specify the extensions, this rule actually validates against the MIME type of the file by reading the file's contents and guessing its MIME type. That's why it's enough to have jpeg to be validated for MIME type image/jpeg, which also covers .jpg extension.

Read more about MIME types here.


Rule 3. size

This rule is interesting because it applies to both string and file fields. In case of string, it validates the length in characters, but if it's a file uploaded, it's validated against file size in kilobytes.

public function rules()
{
    return [
        'photo' => 'image|size:1024', // 1 MB
    ];
}

Rule 4. dimensions

There's even more specific validation, you can restrict min/max width/height of the image.

public function rules()
{
    return [
        'photo' => 'dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000',
    ];
}

Not only that, you can specify a ratio, like 3/2 which would cover 600x400 and 300x200 etc:

public function rules()
{
    return [
        'photo' => 'dimensions:ratio=3/2',
    ];
}

Finally, you can even combine width+height+ratio, it's a little more complicated:

use Illuminate\Validation\Rule;

Validator::make($data, [
    'avatar' => [
        'required',
        Rule::dimensions()->maxWidth(1000)->ratio(3/2),
    ],
]);

So, these are four rules, which are easy to apply. Find more validation rules in the official documentation.

avatar
N SOLOMON SUDHIR Prabhakar

for image validation under size you mentioned as size:1024 which trows error if the uploaded image size is not exactly 1024. It should be max:1024.

👍 3

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 67 courses (1172 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses