DEV Community 👩‍💻👨‍💻

Morcos Gad
Morcos Gad

Posted on

Old Validation ( dimensions ) - Laravel

Today we will learn about this validation very important thing that makes us control the dimensions of the images uploaded to our project. It is old after something, but it is not known to some developers.
Visit the sources :-
https://laravel.com/docs/9.x/validation#rule-dimensions
https://mattstauffer.com/blog/image-dimension-validation-rules-in-laravel-5-3/

  • Here we learn about the properties that we will use while checking the dimensions of the image
In Laravel 5.3, we have a new validation option: image dimensions for image uploads
The validation rule is called dimensions, and you can pass the following parameters to it 

min_width: Images narrower than this pixel width will be rejected
max_width: Images wider than this pixel width will be rejected
min_height: Images shorter than this pixel height will be rejected
max_height: Images taller than this pixel height will be rejected
width: Images not exactly this pixel width will be rejected
height: Images not exactly this pixel height will be rejected
ratio: Images not exactly this ratio (width/height, expressed as "width/height") will be rejected

Enter fullscreen mode Exit fullscreen mode
  • Now, let's make our ImageController and take a look at a few sample validations
 public function postImage(Request $request)
 {
        $this->validate($request, [
             'avatar' => 'dimensions:min_width=250,min_height=500'
        ]);

        // or... 

        $this->validate($request, [
             'avatar' => 'dimensions:min_width=500,max_width=1500'
        ]);

        // or...

        $this->validate($request, [
             'avatar' => 'dimensions:width=100,height=100'
        ]);

        // or...

        // Ensures that the width of the image is 1.5x the height
        $this->validate($request, [
             'avatar' => 'dimensions:ratio=3/2'
        ]);
}
Enter fullscreen mode Exit fullscreen mode
  • use the Rule::dimensions method to fluently construct the rule
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

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

I hope you enjoyed the code and I wish you a happy code .

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.