0

When i dd the $request->file('photo') or $request->input('photo') i get null, even if i have the files=>true in FORM::open. I'm using a registration form in login.blade.php and it looks like:

{{FORM::open(['id'=>'registerForm','url'=>'register','files'=>true,'novalidate'])}}
  <h1>Krijo llogari</h1>
  <div>
      {{FORM::text('first_name',null,['class'=>'form-control','required','placeholder'=>'Emri'])}}
  </div>
  <div>
      {{FORM::text('last_name',null,['class'=>'form-control','required','placeholder'=>'Mbiemri'])}}
  </div>
  <div>
      {{FORM::password('password',['class'=>'form-control','placeholder'=>'Fjalëkalimi','required'])}}
  </div>
  <div>
      {{FORM::password('password_confirmation',['class'=>'form-control','placeholder'=>'Konfirmo fjalëkalimin','required'])}}
  </div>
  <div>
      {{FORM::select('acedemical_title_id',array_merge(['0'=>'Zgjedhe titullin akademik'],$academicalTitles),null,['class'=>'form-control','required','style'=>'border-radius:2px'])}}
  </div>
  <br>
  <div>
      {{FORM::select('cpa_id',array_merge(['0'=>'Zgjedhe profesor/asistent'],$cpas),null,['class'=>'form-control','required','style'=>'border-radius:2px'])}}
  </div>
  <br>
  <div>
      {{FORM::text('personal_number',null,['class'=>'form-control','required','placeholder'=>'Numri personal','maxlength'=>'10'])}}
  </div>
  <div>
      {{FORM::email('email',null,['class'=>'form-control','required','placeholder'=>'E-mail'])}}
  </div>
    <div>
        <div class="input-group image-preview">
            <span class="input-group-btn">
                <!-- image-preview-clear button -->
                <button type="button" class="btn btn-default image-preview-clear" style="display:none;">
                    <span class="glyphicon glyphicon-remove"></span> Pastro
                </button>
                    <!-- image-preview-input -->
                <div class="btn btn-default image-preview-input">
                    <span class="glyphicon glyphicon-folder-open"></span>
                    <span class="image-preview-input-title">Zgjedh foton</span>
                    {!! FORM::file('photo') !!}
                </div>
            </span>
        </div>
    </div>
  <br>
  <div>

      {{FORM::submit('Regjistrohu',['class'=>'btn btn-success pull-right'])}}
  </div>

  <div class="clearfix"></div>

  <div class="separator">
    <p class="change_link">Keni llogari?
      <a href="#signin" class="to_register"> Kyçu </a>
    </p>

    <div class="clearfix"></div>
    <br />

    <div>
        <h1><i class="fa fa-xalfa"></i> XALFA - Për krijimin e orarit!</h1>
        <p>©2016 All Rights Reserved. XALFA Inc. Privacy and Terms</p>
    </div>
  </div>
{{FORM::close()}}

While my controller looks like this:

    public function store(Request $request)
{
    try{
        //dd($request->file('photo'));
        $destination_folder = 'Uploads/';

        $validator = Validator::make($request->all(),[
            'first_name' => 'bail|required|alpha|max:190',
            'last_name' => 'bail|required|alpha|max:190',
            'email' => 'bail|required|email|max:190',
            'password'=>'bail|required|confirmed|max:190',
            'personal_number'=>'bail|required|numeric',
            'cpa_id' => 'bail|required|numeric',
            'acedemical_title_id' => 'bail|required|numeric',
            'photo' => 'bail|require|image|mime:jpeg,png|max:1000000',
        ]);

        if($validator->fails()){
            return response()->json([
                'fails'=>true,
                'title'=>'Gabim gjatë validimit!',
                'msg'=>$validator->getMessageBag()->toArray()
            ],400);
        }

        $data = $request->all();
        if($request->hasFile('photo')){
            dd('asdasgasdasd');
            $file = $request->file('photo');

            $filename = $file->getClientOriginalName().'-'.str_random(8);

            $file->move($destination_folder,$filename);

            $data['photo']=$destination_folder.$filename;
        }else{
            dd('nuk hini hiq');
        }


        if($user = Sentinel::register($data)){
            if($activation = Activation::create($user)){
                if($role = Sentinel::findRoleBySlug('user')){
                    $role->users()->attach($user);

                    $this->sendMail($user, $activation->code);

                    return response()->json([
                        'success'=>true,
                        'title'=>'Aktivizimi',
                        'msg'=>'Për të aktivizuar llogarinë tuaj kontrollo postën tuaj elektronike!'
                    ],200);
                }else{
                    return response()->json([
                        'fails'=>true,
                        'title'=>'Gabim internal',
                        'msg'=>'Ju lutemi kontaktoni mbështetësit e faqes!'
                    ],400);
                }
            }
        }else{
            return response()->json([
                'fails'=>true,
                'title'=>'Gabim gjatë regjistrimit',
                'msg'=>'Ju lutemi shikoni për parregullsi në të dhëna!'
            ],400);
        }
    }catch(QueryException $e){
        return response()->json([
            'fails'=>true,
            'title'=>'Gabim në server!',
            'msg'=>'Ju lutem kontaktoni mirëmbajtësit e faqes.',
        ],500);
    }
    catch(ErrorException $e){
        return response()->json([
            'fails'=>true,
            'title'=>'Gabim në server!',
            'msg'=>'Ju lutem kontaktoni mirëmbajtësit e faqes.'
        ],500);
    }

}

My ajax javascript code looks like:

$('#registerForm').submit(function(e){
    e.preventDefault();

    $.ajaxSetup({
        headers:{
            'X-CSRF-TOKEN': $('meta[name=csrf-token]').attr('content')
        }
    });

    var form = $(this), formData=form.serialize(), url=form.attr('action');

    $.ajax({
        type: 'POST',
        url: url,
        data: formData,
        dataType: 'JSON',
        statusCode: {
            500: function(data){
                BootstrapDialog.show({
                    title: data.responseJSON['title'],
                    message: data.responseJSON['msg'],
                    buttons: [{
                        label: 'Close',
                        action: function(dialog) {
                            dialog.close();
                        }
                    }]
                });
            },
            400: function(data){
                var msg="";
                $.each(data.responseJSON['msg'], function(index, value){
                    $.each(this,function(i,v){
                        msg += v+'\n';
                    })
                });
                BootstrapDialog.show({
                    title: data.responseJSON['title'],
                    message: msg,
                    buttons: [{
                        label: 'Close',
                        action: function(dialog) {
                            dialog.close();
                        }
                    }]
                });
            },
            200: function(data){
                BootstrapDialog.show({
                    title: data.responseJSON['title'],
                    message: data.responseJSON['msg'],
                    buttons: [{
                        label: 'Close',
                        action: function(dialog) {
                            dialog.close();
                        }
                    }]
                });
            }
        }
    });
});

My route file looks like:

Route::post('register','UsersController@store');
Arlind Hajdari
  • 465
  • 1
  • 7
  • 14
  • Possible duplicate of [how to do file upload using jquery serialization](http://stackoverflow.com/questions/4545081/how-to-do-file-upload-using-jquery-serialization) –  Mar 27 '17 at 16:33
  • I'm not uploading the photo with ajax, im just using a response from controller if the file is uploaded or not to the ajax to show it instantly. And in the controller i cant access the file. – Arlind Hajdari Mar 27 '17 at 16:36

2 Answers2

0

e.preventDefault() at the javascript was disabling the input type file request to be sent to controller.

Arlind Hajdari
  • 465
  • 1
  • 7
  • 14
  • I think that's what Neat was hinting at. You were preventing the native form submission and sending the serialized data with AJAX, but "Data from file select elements is not serialized." See [.serialize()](http://api.jquery.com/serialize/). – showdev Mar 27 '17 at 17:29
0

To fetch the input type=file data from ajax instead of serializing the form just create a new object of FormData like this:

var data = new FormData(this)

Where 'this' is the form. Thanks for answers

Arlind Hajdari
  • 465
  • 1
  • 7
  • 14