我正在尝试将图像dimensions validation rule用于控制器内的上传图像:
namespace App\Http\Controllers;
use App\ClassCategory;
use App\Http\Requests;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Validator;
class ClassCategoryController extends Controller {
public function store(Request $request) {
$validator = Validator::make($request->all(), [
'image' => 'dimensions:min_width=300,min_height=300'
]);
if ($validator->fails()) { // This is where the expection is thrown.
// ...
}
}
}
但它引发了以下异常:
BadMethodCallException in Validator.php line 3181:
Method [validateDimensions] does not exist.
in Validator.php line 3181
at Validator->__call('validateDimensions', array('image', 'ballet.jpg', array('min_width=100', 'min_height=200'), object(Validator))) in Validator.php line 484
at Validator->validate('image', 'Dimensions') in Validator.php line 424
at Validator->passes() in Validator.php line 449
at Validator->fails() in ClassCategoryController.php line 42
at ClassCategoryController->store(object(Request))
at call_user_func_array(array(object(ClassCategoryController), 'store'), array(object(Request))) in Controller.php line 80
at Controller->callAction('store', array(object(Request))) in ControllerDispatcher.php line 146
at ControllerDispatcher->call(object(ClassCategoryController), object(Route), 'store') in ControllerDispatcher.php line 94
at ControllerDispatcher->Illuminate\Routing\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 52
...
班级Controller
使用Illuminate\Foundation\Validation\ValidatesRequests
。我在这里缺少什么?
更新
为了将来参考,我收到了another exception,因为我的表单中没有包含enctype
attribute。如果您要上传文件,则需要这样做:
<form enctype="multipart/form-data" method="post"></form>
答案 0 :(得分:1)
如果您使用的是不同版本的Laravel,则可能会发生这种情况。您是否检查过您使用的是Laravel 5.2而不是旧版本(如Laravel 5.1,dimensions
无法使用)。
您可以通过运行以下artisan
命令检查您的版本:
php artisan --version
然后您应该看到类似的内容:
Laravel Framework version 5.2.29
<强>更新强>
运行composer update
下载Laravel v5.2.32
。
您可以通过运行命令grep -ri 'validateDimensions' vendor/*
来验证该方法是否存在,您应该看到:
vendor/laravel/framework/src/Illuminate/Validation/Validator.php: protected function validateDimensions($attribute, $value, $parameters)
此功能仅添加到Laravel recently,并于2016年5月17日在Laravel v5.2.32中发布。
答案 1 :(得分:0)
PHP 每个文件使用use
关键字来导入已使用的部分。
所以你必须声明
use Illuminate\Foundation\Validation\ValidatesRequests;
语句。
然后将use
语句添加到类中,如下所示:
class ClassCategoryController extends Controller {
use ValidatesRequests;
public function store(Request $request) {.....