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

libertey's avatar

validate aspect ratio laravel

Hello, i try to make an upload form the user should only upload an image with a given aspect ratio, i have an algorithm which calculates that, now i wanna validate it but if the dimensions are perfectly fine it always throws my error message and does not store the image, im using 4:3 AR and 1:1 AR the 1:1 is working great only the 4:3 does make some trouble. Do you know why it throws always the error?

These are the sizes i use to calcultae they are coming from the model.

    public const IMAGE_WIDTH = 1280;
    public const IMAGE_HEIGHT = 960;

This is the validtion rule inside my StoreRequest Class.

'image'         => 'mimes:jpg,jpeg,png|dimensions:min_width=' . City::IMAGE_WIDTH  . ',min_height=' . City::IMAGE_HEIGHT . ',ratio=' . getAspectRatio(City::IMAGE_WIDTH, City::IMAGE_HEIGHT)['aspect'],

And the algorithm to calc Aspect Ratio.

function getAspectRatio($width, $height): array
{
    function getDivisorList($px): array
    {
        $list = [];
        $i = 1;

        while($px / $i >= 1) {
            if ($px % $i === 0) {
                $div = $px / $i;
                $list[$div] = $px / $div;
            }
            $i++;
        }
        return $list;
    }

    $w = getDivisorList($width);
    $h = getDivisorList($height);

    $aspect = "";
    $ratio = 0;

    foreach ($w as $div => $num) {
        if (isset($h[$div])) {
            $aspect = $num . ":" . $h[$div];
            $ratio = $num / $h[$div];
            break;
        }
    }

    return ['aspect' => $aspect, 'ratio' => $ratio];
}

If anyone could help i would appreciate it :)!

0 likes
1 reply
libertey's avatar
libertey
OP
Best Answer
Level 1

Nevermind found the error was just laravel needs a slash (/) if you wan't to validate AR i used it with (:) so needed to change the return value in algorithm function and now it work's.

//From this 
$aspect = $num . ":" . $h[$div];

//To This
$aspect = $num . "/" . $h[$div];

Please or to participate in this conversation.