'How to validate a file type in laravel
I need to validate that a user only uploads a .jpg
I have the following request class. I made the image required but don't know how to check that it is only .jpg
public function rules()
{
return [
'name' => 'required|min:3',
'sku' => 'required|min:5|unique:products',
'description' => 'required|min:20',
'price' => 'required',
'image' => 'required'
];
}
Solution 1:[1]
Does it have to just be .jpg? If so then something like:
'image' => 'required|mimes:jpeg'
Documentation: http://laravel.com/docs/5.1/validation#rule-mimes
If it can be any type of image, then:
'image' => 'required|image'
Documentation: http://laravel.com/docs/5.1/validation#rule-image
Solution 2:[2]
Solution 3:[3]
You can create new validation rule:
<?php
declare(strict_types=1);
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Http\UploadedFile;
class FileType implements Rule
{
public function __construct(protected array $acceptedTypes)
{
}
/**
* @param $attribute
* @param UploadedFile $value
* @return bool
*/
public function passes($attribute, $value): bool
{
try {
$mimeType = $value->getMimeType();
preg_match('/^(.*)\//', $mimeType, $res);
$type = $res[1];
return in_array($type, $this->acceptedTypes);
} catch (\Throwable) {
return false;
}
}
public function message(): string
{
$types = implode(', ', $this->acceptedTypes);
return 'File type invalid, accepted types: ' . $types;
}
}
'file' => [
'required',
'file',
'max:50240',
new FileType(['audio', 'video'])
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Thomas Jensen |
Solution 2 | saad |
Solution 3 | George |