1

Im making an inventory system in laravel and I want to upload an image every products that I have. My problem is I cant upload an image. I tried my old code in uploading photo and it is not working in my current project. The upload code you see in the controller is in a laravel collective form. But now, I am using a modal and an ajax request to save the inputs into the database. Can someone know what should I do about this? Btw, my modal doesnt have a form tag because I thought forms will not work in modals. Thanks in advance!

Modal Create.

     <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
                    <div class="modal-dialog modal-dialog-centered" role="document">
                      <div class="modal-content">
                        <div class="modal-header">
                          <h5 class="modal-title" id="exampleModalCenterTitle">Register New Product</h5>
                          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                          </button>
                        </div>
                        <div class="modal-body">
                        <p style="font-weight: bold;">Name </p>
                          <input   type="text" class="form-control" id="product_name"/>
                          <p style="font-weight: bold;">Description </p>
                          <input   type="text" class="form-control" id="description"/>

                          <p style="font-weight: bold;">Price </p>
                          <input   type="text" class="form-control" id="currentprice"/>
                          {{-- <input style="text-transform:uppercase"   type="text" class="form-control" id="supplier_id"/> --}}
                          <p style="font-weight: bold;">Supplier </p>
                          <select class="form-control"  id="supplier_id"  >
                              @foreach ($suppliers as $supplier)
                          <option value="{{$supplier->id}}">{{$supplier->name}}</option>
                              @endforeach
                              </select>
                         <p style="font-weight: bold;">Picture </p>
                          <input  type="file" class="form-control" id="picture"/>
                        </div>
                        <div class="modal-footer">
                          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                          <button type="button" class="btn btn-primary" id="add_product">Add</button>
                        </div>
                      </div>
                    </div>
                  </div>

Controller

    public function store(Request $request)
    {
        $data = $request->all();
        $data['product_name'] = ($data['product_name']);
        $data['description'] = ($data['description']);
        $data['supplier_id'] = ($data['supplier_id']);
        $data['price'] = ($data['price']);



        if ($request->hasFile('image')){
            //Add new photo
                $image = $request->file('image');
                $filename = time() . '.' . $image->getClientOriginalExtension();
                $location = public_path('img/' . $filename);
                Image::make($image)->resize(300,300)->save($location);
                $oldFilename = $products->image;
            //Update DB
                $products->image = $filename;
             //Delete the old photo
                // Storage::delete($oldFilename);
            }

        Product::create($data);
        return response()->json($data);
    }

Ajax

   $(document).ready(function(){
                //add
                $('#add_product').click(function(e){
                    e.preventDefault();
                    var name = $('#product_name').val();
                    var description = $('#description').val();
                    var price = $('#currentprice').val();
                    var supplier_id = $('#supplier_id').val();
                    var image = $('#picture').val();

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

                    $.ajax({
                        url: "{{    url('/product')     }}",
                        method: 'post',
                        data:{
                            product_name: name,
                            description: description,
                            price: price,
                            supplier_id: supplier_id,
                            image: image,
                        },
                        success: function (res){
                            console.log(res);
                            window.location.href = '{{route("products")}}'
                        }
                    });

                });
                //add

Model

class Product extends Model
{
    use SoftDeletes;
    protected $fillable = [
        'product_name', 'quantity', 'description' ,'supplier_id', 'price', 'image',
    ];

    public function supplier()
    {
        return $this->hasOne('App\Supplier');
    }
}

draw134
  • 1,053
  • 4
  • 35
  • 84
  • 2
    In Ajax code where the `image` variable is defined – lkdhruw Sep 24 '19 at 15:15
  • Okay sir i think i forgot to define the `image` variable. Ill tell you whats the result in a minute – draw134 Sep 24 '19 at 15:17
  • There are no errors sir when i add this code `var image = $('#picture').val();` and when i look in the database, the image name was in like this ` C:\fakepath\59838793_482825115589519_4600609237641461760_n.jpg` . And there is no image in my `public/img` directory – draw134 Sep 24 '19 at 15:22
  • This might help https://stackoverflow.com/a/20285053/2669814 – lkdhruw Sep 24 '19 at 15:39

1 Answers1

0

I Can’t add a comment, that is dumb ...

Your also going to likely need to encode the image data in the json.

See How do you put an image file in a json object?

(Fixed wording)

Terre Porter
  • 63
  • 2
  • 9
  • You might try adding these to you Ajax, enctype: 'multipart/form-data', processData: false, contentType: false – Terre Porter Sep 24 '19 at 15:40
  • The first tells the server you have a mixed data being submitted. The processData tells query to not “process” the data being sent, the contentType tells jquery to not change the type. – Terre Porter Sep 24 '19 at 15:46
  • ahh i see. I put the code you wanted me to and now it returns an error . I cant insert anymore – draw134 Sep 24 '19 at 15:48
  • tha error is `Undefined index: product_name` in my controller `store` method. I think there was nothing wrong with it – draw134 Sep 24 '19 at 15:49
  • Hum, ok. Try setting the content type to, contentType: "multipart/form-data”. Also, might need to use https://developer.mozilla.org/en-US/docs/Web/API/FormData – Terre Porter Sep 24 '19 at 15:55
  • how does `formData` work? and how could i implement it on my ajax? – draw134 Sep 24 '19 at 15:57
  • ahh it gets me an error again. `Missing boundary in multipart/form-data POST data` `Undefined index: product_name`. what to dooo. i might end up whole day fixing this hahha – draw134 Sep 24 '19 at 15:59
  • https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects Has some example code. Also try searching for “jquery Ajax file upload” it can be tricky but there are some jquery plugins that might work – Terre Porter Sep 24 '19 at 16:00
  • btw sir thanks for your time. i think its hard for me to fix this but ill try some methods that u suggested, – draw134 Sep 24 '19 at 16:02
  • 1
    No problem. I am sure you will figure it out. – Terre Porter Sep 24 '19 at 16:10