在我的laravel 5.6应用程序中,我的控制器具有这样的图像存储功能,
public function store(Request $request)
{
$image = new Category();
if ($request->hasFile('image')) {
$dir = 'images/';
$extension = strtolower($request->file('image')->getClientOriginalExtension()); // get image extension
$fileName = str_random() . '.' . $extension; // rename image
$request->file('image')->move($dir, $fileName);
$image->categoryimage = $fileName;
}
$image->save();
}
现在,如果没有图像保存(空)并且文件格式等于(png,jpeg,png),那么在保存图像之前我需要先进行验证。我该怎么办?
答案 0 :(得分:1)
函数的第一行
$validatedData = $request->validate([
'image' => 'required|file|mimes:jpeg,png'
]);
//image is valid
看看这个:docs
答案 1 :(得分:1)
您可以这样做:
//first you should use the Request class at the top of your file
use Illuminate\Http\Request;
public function store(Request $request)
{
$validator = $request->validate([
'image' => 'required|image'
]);
if ($validator->fails()) {
// write what you want here
}
// the rest of your code
}
正在验证的文件必须是图像(jpeg,png,bmp,gif或svg)。