How to Add File Size Validation in Laravel

AuthorSumit Dey Sarkar

Pubish Date22 Mar 2023

categoryLaravel

In this tutorial we will learn how to add file size validation in laravel.

 

How to add file size validation in laravel

To add file size validation in Laravel, need to use the `size` validation rule which provided by Laravel already. Size validation rule allows you to validate the maximum file size of an uploaded file.

Here's an example of how you can add file size validation to a file upload request in Laravel:

 

1) First, add a file input field to your form:

<form method="POST" action="{{ route('upload-file') }}" enctype="multipart/form-data">
    @csrf
    <input type="file" name="file">
    <button type="submit">Upload</button>
</form>

 

2) In your controller, add a validation rule for the `file` input using the `size` rule:

public function uploadFile(Request $request)
{
    $request->validate([
        'file' => 'required|file|max:1024', // Maximum file size in kilobytes
    ]);

    // Process file upload...
}

In this example, the `size` rule is used to ensure that the uploaded file is no larger than 1024 kilobytes (or 1 megabyte).

 

You can adjust the maximum file size as needed by changing the value passed to the `max` rule.

Comments 0

Leave a comment