jeudi 10 mars 2016

Laravel form validation in image upload with ajax

I am working in laravel 5. and using blade and ajax for upload image. Every thing was working fine unless I inserted validation code in store function inside controller. Getting server error:

POST http://localhost:8000/imgC 500 (Internal Server Error)

I guess there is something wrong with url inside ajax or in routes, I am using Restfull Controller.

image.blade.php

{{Form::open(array('url' => 'imgC', 'method' => 'post','files'=>true, 'id'=>'upload_form'))}}
   Title: {{Form::text('title')}}
   Image: {{Form::file('image')}}
   {{Form::submit('submit',['id' => 'btnAddProduct'])}}
   {{Form::close()}}

ImageController.php:

public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'name' => 'required|max:255',
    ]);

    if ($validator->fails()) {
        return "error";
    }
    $destinationpath = public_path() . '/img/';
    $image=$request->input('image');
    $filename=$request->file('image')->getClientOriginalName();
    $request->file('image')->move( $destinationpath,$filename );


    $img= new Image;
    $img->name= $request->input('title');
    $img->picture_path=$filename;

    $saveflag=$img->save();
    if($saveflag){
        return Response::json(['success' => $saveflag, 'file' => asset($destinationpath.$filename)]);
    }

}

AJAX function:

$(document).ready(function() {
  $('#upload_form').submit(function (event) {
      event.preventDefault();
      $.ajax({
          url: '/imgC',
          data: new FormData($(this)[0]),
          type: "POST",
          processData: false,
          contentType: false
      }).done(function (response) {
          console.log(response);
          $("#success").show();
          setTimeout(function() { $("#success").hide(); }, 5000);

      });
  });
});

route.php:

Route::resource('imgC', 'ImageController');

What am I doing wrong here?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire