Image Validation in Laravel

Laravel has a few rules for the validation of images:

let’s say we have a controller called UploadController. The upload operation takes happen here.

class UploadController extends Controller
{


    public function store()
    {
        
       //upload the image 

    }

}

and a view file that has a form for selecting the image:

<div>
    <form action="{{route('upload')}}" >
        <label for="">Select Your File</label>
        <input type="file" name="picture">
        <button type="submit" class="btn btn-primary">Upload</button>

    </form>
</div>

we use validate() method on request() to validate the data that is sent from the user.

by using the image validation rule the uploaded file should be only jpg, jpeg, png, bmp, gif, svg, or webp.

class UploadController extends Controller
{


    public function store()
    {

        request()->validate([
            'picture' => 'image'
        ]);


    }

}

Validate Image Size

we can validate the size with the size rule:

class UploadController extends Controller
{
    public function store()
    {
        request()->validate([
            'picture' => 'image|size:2048'
        ]);

    }

}

the image size is in kilobytes. in the above code, the image size should be less than 2048 kilobytes.

Validating mime type

sometimes we want the image to be only in certain formats so we have to use the mimes rule:

class UploadController extends Controller
{

    public function store()
    {
        request()->validate([
            'picture' => 'mimes:png,jpeg'
        ]);

    }

}

Validating Dimensions of the Image

using the dimensions rule we can limit the width and height of the image being uploaded:

class UploadController extends Controller
{


    public function store()
    {
        request()->validate([
            'picture' => 'dimensions:max_with=500,max_height=500'
        ]);

    }

}

with dimensions rule we can use max_width, min_width, max_height, min_height, height, width and ratio.

this is another example using dimensions with ratio:

class UploadController extends Controller
{


    public function store()
    {
        request()->validate([
            'picture' => 'dimensions:ratio=5/2'
        ]);

    }

}

ratio=5/2 means that width divided by height should be 5/2 or 2.5

these rules are for validating images. there are more rules for validating files in general. you can read about them in Laravel documentation.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *