Tohid Dadashnezhad
Tohid Dadashnezhad

Reputation: 1938

Laravel 5.1 file upload validation

I want to upload an image file using

 {!! Form::open(['url'=>'admins']) !!}
  {!! Form::input('file','photo',null,['class'=>'photo_input']) !!} 

Also my validation rules are

 public function rules()
{
    return [
       'username'=>'required|max:127|min:3|unique:users,username,'.$this->username,
       'email'=>'required|max:127|email|min:3|unique:users,email,'.$this->email,
       'password'=>'required|max:127|min:5|confirmed',
       'password_confirmation'=>'required|max:127|min:5|',
       'role'=>'required|max:127|min:5|in:programmer,admin,employee',
       'photo' => 'mimes:jpg,jpeg,bmp,png,gif'
    ];
}

But I get an error

The photo must be a file of type: jpg, jpeg, bmp, png, gif.

Whereas the file extension which I choose is jpg, so what's wrong?

Upvotes: 3

Views: 1721

Answers (3)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

The reason behind is you need to define within your form tag the attribute enctype = "multipart/form-data". So while using Laravel 5.X Form Facade you need to pass the attribute files => true within your array of form open like as

{!! Form::open(['url'=>'admins','files' => true]) !!}
                              //^^^^^^^^^^^^^^^^ added

Source Docs

Upvotes: 1

Tohid Dadashnezhad
Tohid Dadashnezhad

Reputation: 1938

I fixed it, the reason was that I have not added enctype to the form.

{!! Form::open(['url'=>'admins','enctype'=>'multipart/form-data']) !!}

Upvotes: 0

Envision eCommerce
Envision eCommerce

Reputation: 101

This issue is also caused due to uploading large file size then the allowed in the php.ini

Please check

upload_max_filesize

and

post_max_size

in php.ini

You can also validate the Image size by extending the Validator

In Your Controller
Validator::extend('img_upload_size', function($attribute, $value, $parameters)
{
 $file = Request::file($attribute);
 $image_size = $file->getClientSize();
 if( (isset($parameters[0]) && $parameters[0] != 0) && $image_size > $parameters[0]) return false;
 return true;
});


In Validation Rules
 return [
 'username'=>'required|max:127|min:3|unique:users,username,'.$this->username,
    'email'=>'required|max:127|email|min:3|unique:users,email,'.$this->email,
    'password'=>'required|max:127|min:5|confirmed',
    'password_confirmation'=>'required|max:127|min:5|',
    'role'=>'required|max:127|min:5|in:programmer,admin,employee',
 'photo' => 'required|mimes:jpeg,bmp,png|img_upload_size:1000000',//!MB
]

Upvotes: 0

Related Questions