33

I'm new to Laravel. I have a form with a File upload function on it. How can I validate their file? I will only allowed Microsoft Word files. Here's my validation code.

I just want check if they insert a ms word file and if not it will not be processed.

public function store()
{
  // Validate
    $rules = array(
        'pda'                         => 'required|unique:forms',
        'controlnum'                  => 'required|unique:forms',
        'date'                        => 'required',
        'churchname'                  => 'required',
        'title'                       => 'required',
        'pastorname'                  => 'required',
        'contactnum'                  => 'required',
        'address'                     => 'required',
        'state'                       => 'required',
        'region'                      => 'required',
        'area'                        => 'required',
        'city'                        => 'required',
        'zipcode'                     => 'required|numeric|max:9999',
        'tgjteachertraining'          => 'required',
        'localcontact'                => 'required',
        'tgjdatestart'                => 'required',
        'tgjdateend'                  => 'required',
        'tgjcourse'                   => 'required|numeric',
        'childrengraduated'           => 'required|numeric|max:450',
        'childrenacceptjesus'         => 'required|numeric',
        'howmanycomitted'             => 'required|numeric',
        'recievedbibles'              => 'required|numeric',
        'descgradevent'               => 'required',
        'whatwillyoudo'               => 'required',
        'pastortest'                  => 'required',
        'teachertest'                 => 'required',
        'childrentest'                => 'required',
        'file'                        => 'required|max:10000',
    );

    $validator = Validator::make(Input::all(), $rules);

    // process the form
    if ($validator->fails()) {
        return Redirect::to('forms/create')->withErrors($validator);
    } else {
        // store
        $forms = new Forms;
        $forms->pda                         = Input::get('pda');
        $forms->controlnum              = Input::get('controlnum');
        $forms->date                = Input::get('date');
        $forms->churchname                  = ucwords(Input::get('churchname'));
        $forms->title                       = ucwords(Input::get('title'));
        $forms->pastorname                  = ucwords(Input::get('pastorname'));
        $forms->address                     = Input::get('address');
        $forms->contactnum                  = Input::get('contactnum');
        $forms->state                       = Input::get('state2');
        $forms->region                      = Input::get('region2');
        $forms->area                        = Input::get('area2');
        $forms->citytown                    = Input::get('city2');
        $forms->zipcode                     = Input::get('zipcode');
        $forms->tgjteachertraining          = Input::get('tgjteachertraining');
        $forms->localcontact            = ucwords(Input::get('localcontact'));
        $forms->tgjdatestart            = Input::get('tgjdatestart');
        $forms->tgjdateend              = Input::get('tgjdateend');
        $forms->tgjcourse           = Input::get('tgjcourse');
        $forms->childrengraduated           = Input::get('childrengraduated');
        $forms->childrenacceptjesus     = Input::get('childrenacceptjesus');
        $forms->howmanycomitted         = Input::get('howmanycomitted');
        $forms->recievedbibles          = Input::get('recievedbibles');
        $forms->descgradevent           = Input::get('descgradevent');
        $forms->whatwillyoudo           = Input::get('whatwillyoudo');
        $forms->pastortest          = Input::get('pastortest');
        $forms->teachertest             = Input::get('teachertest');
        $forms->childrentest            = Input::get('childrentest');
        $file                   = Input::file('file');
        $filename                   = $file->getClientOriginalName(); 
        $destinationPath                = 'uploads/'.Input::get('pda');
        $uploadSuccess              = Input::file('file')->move($destinationPath, $filename);
        $forms->docurl              = 'uploads/'.Input::get('pda').'/'.$filename;
        if( $uploadSuccess ) {
        $forms->save();
        //Session::flash('message', 'Successfully submitted form!');
        return Redirect::to('forms/create'); 
        Session::flash('message', 'Successfully submitted form!');

        } 
        else {
        return Response::json('error', 400);
        }
    }
}

3 Answers 3

65

To validate mime type of a file input in Laravel you can use the mimes rule. Remember to match the mime type detected with the actual mime of file you provide. It may vary on different servers.

For example, you want to enable adding and word document in you form:

1) in config/mimes.php add the below mime types:

    'doc'  => array('application/msword', 'application/vnd.ms-office'),
    'docx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip'), 

2) in your validation $rules add the following elements:

    'file' => 'required|max:10000|mimes:doc,docx' //a required, max 10000kb, doc or docx file
Sign up to request clarification or add additional context in comments.

6 Comments

yes, create it and filll similarily to the rest of config files, as an array of keys. As for the keys - that is what I included in my answer :)
Hi Thanks! I did what you said and follow this github.com/jasonlewis/laravel.com/blob/master/application/… But I still got Error:
LogicException Unable to guess the mime type as no guessers are available (Did you enable the php_fileinfo extension?)
well it seems you have your server underconfigurted, you are missing some extensions required for mime type detection ? What is your HTTP server stack and opearting system? By the way, if my answer solved your initial question, please accept it as official answer so others can also benefit when they encounter similar problems. Cheers!
Hi! I managed it to work. Thanks! I just forgot to enable some extension in my wamp server. Thanks! I give you a plus :)
|
4

As of Laravel 9.22 you can write the validation rules a lot shorter and more readable like:

'file' => ['required', File::types(['doc', 'docx'])->smallerThan(10000)]

You can find the available methods in this pr: https://github.com/laravel/framework/pull/43271

1 Comment

As of Laravel 10, smallerThan() seems to have been replaced by min() and max(). See Laravel 10: File Validation.
3

Try this?

'file' => 'required|max:10000|mimes:application/vnd.openxmlformats-officedocument.wordprocessingml.document'

You may want to set some custom message for the response though :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.