DEV Community

Asif
Asif

Posted on

Validating Base64 Images by Size in Laravel: A How-to Guide

As Laravel developers, we often need to validate uploaded images to ensure they meet certain size requirements. Out of the box, Laravel's validation rules like max only work on numeric values, not base64-encoded images.

In this post, we'll walk through extending Laravel's validation to handle custom base64 image size validation. By writing a custom validation rule, we can reuse this logic anywhere image uploads are required in our app.

Custom Validation Rule

All custom validation rules are registered by extending the Validator in the boot method of our AppServiceProvider. First, we'll use Laravel's Validator::extend method to define the logic:

Validator::extend('base64_image_size', function ($attribute, $value, $parameters, $validator) {

  // Decode the image
  $decodedImage = base64_decode($value);

  // Get image size in kilobytes 
  $imageSize = strlen($decodedImage) / 1024;

  // Check if image is below max size
  return $imageSize <= $parameters[0]; 

});
Enter fullscreen mode Exit fullscreen mode

Here we are decoding the base64-encoded image to get its binary size in bytes. Then we convert to kilobytes to compare against the maximum size defined in the parameters. If the image is below the max size, the validation passes.

Custom Error Messages

Next, we'll customize the error message using the Validator::replacer method:

Validator::replacer('base64_image_size', function ($message, $attribute, $rule, $parameters) {
  return str_replace([':attribute', ':max'], [$attribute, $parameters[0]], $message);
});
Enter fullscreen mode Exit fullscreen mode

This replaces :attribute with the field name and :max with the defined max size. The message itself is defined in the resources/lang/xx/validation.php language file:

'base64_image_size' => 'The :attribute must not be larger than :max KB.',
Enter fullscreen mode Exit fullscreen mode

Usage

Finally, we can use this custom rule during validation:

$validator = Validator::make($request->all(), [
  'image' => 'required|base64_image_size:500',
]);

if ($validator->fails()) {
  // Image too large
} 
Enter fullscreen mode Exit fullscreen mode

By extending Laravel's validation capabilities, we've built a reusable way to validate base64 image sizes across our application. The same approach can be used for any validation logic that doesn't fit neatly into the built-in rules.

Top comments (0)

The discussion has been locked. New comments can't be added.