Search code examples
phplaravellaravel-5laravel-validation

Dimensions validation rule cannot find validateDimensions()


I'm trying to use the image dimensions validation rule for uploaded images inside a controller:

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.
      // ...
    }
  }
}

But it throws the following exception:

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
...

The class Controller uses Illuminate\Foundation\Validation\ValidatesRequests. What am I missing here?

UPDATE

For future reference, I was getting another exception because I didn't include the enctype attribute in my form. This is needed if you're uploading files:

<form enctype="multipart/form-data" method="post"></form>

Solution

  • This is likely to happen if you are using a different version of Laravel. Have you checked that you are using Laravel 5.2 and not a older version (like Laravel 5.1, where dimensions wasn't available).

    You can check your version by running the following artisan command:

    php artisan --version
    

    You should then see something like:

    Laravel Framework version 5.2.29
    

    UPDATE

    Run composer update to download Laravel v5.2.32.

    You can verify that the method exists by running the command grep -ri 'validateDimensions' vendor/* and you should see:

    vendor/laravel/framework/src/Illuminate/Validation/Validator.php:    protected function validateDimensions($attribute, $value, $parameters)
    

    This function was only added to Laravel recently, and was released in Laravel v5.2.32 on 17th May 2016.