mouse's avatar
Level 1

Laravel does not update image.

I have a product form where I can add new products. All is work expect the uploading image where I got default.jpg value in mysql and I do not understand where is the problem. Can you help me, please?

table:

 public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('pid');
            $table->string('pslug')->nullable();
            $table->string('ptitle');
            $table->text('pdescription');
            $table->string('pcat');
            $table->integer('par');
            $table->integer('pdb');
            $table->string('pcikkszam');
            $table->string('avatar')->default('default.jpeg');
            $table->timestamps();
        });
    }

Form:

<div id="prodModal" class="modal fade" role="dialog">
            <div class="modal-dialog">
                <!-- Modal content-->
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title"></h4>
                    </div>
                    <div class="modal-body">
                        <form class="form-horizontal" role="form">
                            <div class="form-group">
                                <div class="col-sm-10">
                                    <input type="hidden" class="form-control" id="pid" disabled>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-sm-10">
                                    <input type="hidden" class="form-control" id="pslug" disabled>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-sm-2" for="pname">Termék neve:</label>
                                <div class="col-sm-10">
                                    <input type="name" class="form-control" id="ptitle">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label" for="pcat">Termékkategória:</label>
                                    <select id="pcat" name="pcat">
                                        @foreach($categories as $category)
                                            <option value="{{ $category->cid }}"> {{ $category->cname }} </option>
                                        @endforeach
                                    </select>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-sm-2" for="pcikksz">Ár:</label>
                                <div class="col-sm-10">
                                    <input type="name" class="form-control" id="par">
                                </div>
                            </div>
                             <div class="form-group">
                                <label class="control-label col-sm-2" for="pname">Darabszám:</label>
                                <div class="col-sm-10">
                                    <input type="name" class="form-control" id="pdb">
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-sm-2" for="pcikksz">Cikkszám:</label>
                                <div class="col-sm-10">
                                    <input type="name" class="form-control" id="pcikkszam">
                                </div>
                            </div>
                             <div class="form-group">
                                <label class="control-label col-sm-2" for="pcdescr">Leírás:</label>
                                <div class="col-sm-10">
                                    <textarea  id="pdescription" name="pdescription" class="form-control" rows="5" required></textarea>
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="control-label col-sm-2" for="pcdescr">Kép:</label>
                                <div>
                                    <div class="col-sm-10">
                                        <input type="file" id="avatar" name="avatar"><br />
                                    </div>
                                </div>
                            </div>
                        </form>
                        <div class="deleteContent">
                            Are you Sure you want to delete <span class="iname"></span> ? <span
                                class="hidden piid"></span>
                        </div>
                        <div class="modal-footer">
                             <button type="button" class="btn actionBtn-btn" data-dismiss="modal">
                                <span id="footer_action_button-btn" class='glyphicon'> </span>
                            </button>
                            <button type="button" class="btn btn-warning" data-dismiss="modal">
                                <span class='glyphicon glyphicon-remove'></span> Close
                            </button>
                        </div>
                    </div>
                </div>
            </div>

Controller:

public function pstore(ProductFormRequest $request)
    {
        $pslug = uniqid();
        $product = new Item();
        $product->ptitle = $request->ptitle;
        $product->pdescription = $request->pdescription;
        $product->pcat = $request->pcat;
        $product->par = $request->par;
        $product->pdb = $request->pdb;
        $product->pcikkszam = $request->pcikkszam;
        $product->pslug = $pslug;

        if($request->hasFile('avatar')){
            $avatar = $request->file('avatar');
            $filename = time() . '-' . $avatar->getClientOriginalExtension();
            Image::make($avatar)->resize(300, 300)->save( public_path('/img/product_img/' . $filename) );

            $product->avatar = $filename;
            $product->save();
        }

        $product->save();

        return response()->json($product);
    }


public function pedit($pslug)
    {
        $product = Item::where('pslug', $pslug)->first();
        return view('admin.termekszerk', compact('product'));
    }

  
    public function pupdate(ProductFormRequest $request, $pslug)
    {
        $product = Item::where('pslug', $pslug)->first();

        $product->ptitle = $request->get('ptitle');
        $product->pcat = $request->get('pcat');
        $product->pcikkszam = $request->get('pcikkszam');
        $product->par = $request->get('par');
        $product->pdb = $request->get('pdb');
        $product->pdescription = $request->get('pdescription');

     if($request->hasFile('avatar')){
            $avatar = $request->file('avatar');
            $filename = time() . '-' . $avatar->getClientOriginalExtension();
            Image::make($avatar)->resize(300, 300)->save( public_path('/img/product_img/' . $filename) );

            $product->avatar = $filename;
            $product->save();
        }


        $product->save();
        return redirect(action('CategoriesController@index', $product->pslug))->with('status', 'A termék frissítve!');

    }
0 likes
19 replies
Youz's avatar

What is supposed to get stored in your avatar field ? Because its seems to work.

mouse's avatar
Level 1

I would like if I upload image then change default.jpg with uploaded image file name. But it does not work. Everytime when I add new product with image, I get default.jpg value and it does not save the image file in the img/product_img folder. @Youz

Youz's avatar

Oh I see :

            $avatar = $request->file('avatar');
            $filename = time() . '-' . $avatar->getClientOriginalExtension();
            Image::make($avatar)->resize(300, 300)->save( public_path('/img/product_img/' . $filename) );

            $product->avatar = $filename;
            $product->save();
        }

This return "default.jpg" at the end ? If you try a dd($filename); after $filename = time() . '-' . $avatar->getClientOriginalExtension();

What is returned ?

Youz's avatar

Maybe that if isn't performed and you got a default value set anywhere ?

mouse's avatar
Level 1

It does not work neither. Now I deleted the ->default('default.jpeg'); in table and I get this error: SQLSTATE[HY000]: General error: 1364 Field 'avatar' doesn't have a default value

Youz's avatar

I think the IF statement isnt executed.

You should add dd('Hello'); in your if.

If you don't see hello, you have an issue with your IF

if($request->hasFile('avatar')){
    dd("Hello");
            $avatar = $request->file('avatar');
            $filename = time() . '-' . $avatar->getClientOriginalExtension();
            Image::make($avatar)->resize(300, 300)->save( public_path('/img/product_img/' . $filename) );

            $product->avatar = $filename;
            $product->save();
        }
mouse's avatar
Level 1

I tried and Unfortunately, I do not see hello. @Youz

Youz's avatar

So try dd($request->all()) before your if to see what your request have :)

mouse's avatar
Level 1

I get this, but it does not insert into the database.

array:9 [
  "_token" => "afTUAT10ENMXn0ltXz1FUTmk30T2VpCHT4j89GSN"
  "pid" => null
  "pcat" => "1"
  "ptitle" => "legújabb"
  "pdb" => "22"
  "pcikkszam" => "c1c1ec1ece1"
  "pdescription" => "clncLNIN NEINFIENFINEFINm wqdniwndiwndinwdin"
  "par" => "55"
  "avatar" => "C:\fakepath\images.jfif"
]
Youz's avatar

Your if($request->hasFile('avatar')) doesn't work. Try something like if($request->avatar)

rob897's avatar

Aren't you missing your encode type if you are uploading a file?

<form class="form-horizontal" role="form" enctype="multipart/form-data">    
2 likes
mouse's avatar
Level 1

@rob897 @Youz Unfortunately these are not work neither. I tried everything. My code is now: in controller:

$avatar = $request->avatar;
        if($avatar) {
            $filename = time() . '-' . $avatar->getClientOriginalExtension();
            Image::make($avatar)->resize(300, 300)->save( public_path('/img/product_img/' . $filename));
            
            $product = new Item();
            $product->avatar = $filename;
            $product->save();
        }

in form:

 <div class="form-group">
   <label class="control-label col-sm-2" for="avatar">Kép:</label>
        <div>
           <div class="col-sm-10">
              <form class="form-horizontal" role="form" enctype="multipart/form-data">  
                 <input type="file" id="avatar" name="avatar"><br />
              </form>
            </div>
        </div>
  </div>

and I get this error: Call to a member function getClientOriginalExtension() on string

rob897's avatar

in your controller if you dd($request->avatar) do you see the getClientOriginalExtension() ? Also I do not see a method in your opening form tag.. So it appears your not hitting the controller.

mr.teapot's avatar

Maybe it is your php settings restricting the file size of uploads, try increasing it in your php.ini.

mouse's avatar
Level 1

@rob897 if I use dd($request->avatar) I do not see getClientOriginalExtension(). I get null.

I created an another form without modal + ajax and the uploading image works. But I need to use modal... this is how looks my form now:

<form class="form-horizontal" method="post" enctype="multipart/form-data">
  <input type="hidden" name="_token" value="{!! csrf_token() !!}">

    
    //  some form-group
    
                           
  <div class="form-group">
    <label class="control-label col-sm-2" for="avatar">Kép:</label>
    <div class="col-sm-10"> 
      <input type="file" name="avatar" id="avatar">
    </div>
  </div>
                       
  <div class="deleteContent">Are you Sure you want to delete <span class="iname"></span> ? <span class="hidden piid"></span>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn actionBtn-btn" data-dismiss="modal">
      <span id="footer_action_button-btn" class='glyphicon'> </span>
   </button>
   <button type="button" class="btn btn-warning" data-dismiss="modal">
     <span class='glyphicon glyphicon-remove'></span> Close
   </button>
  </div>
</form>

controller:

public function pstore(ProductFormRequest $request)
    {
        
        $pslug = uniqid();
        $product = new Item();
        $product->ptitle = $request->ptitle;
        $product->pdescription = $request->pdescription;
        $product->pcat = $request->pcat;
        $product->par = $request->par;
        $product->pdb = $request->pdb;
        $product->pcikkszam = $request->pcikkszam;
        $product->pslug = $pslug;

        
        if ($request->hasFile('avatar')) {
            
            $avatar = $request->file('avatar');
            $filename = time() . '.' . $avatar->getClientOriginalExtension();
            $location = public_path('avatars/' . $filename);
            Image::make($avatar)->resize(800, 400)->save($location);

            $product->avatar = $filename;
       }

        $product->save();
        return response()->json($product);

    }

I have an ajax too. I do not know that maybe it can cause the problem.

$(document).on('click', '.add-modal', function() {
        $('#footer_action_button-btn').text(" Hozzáadás");
        $('#footer_action_button-btn').addClass('glyphicon-check');
        $('#footer_action_button-btn').removeClass('glyphicon-trash');
        $('.actionBtn-btn').addClass('btn-success');
        $('.actionBtn-btn').removeClass('btn-danger');
        $('.actionBtn-btn').addClass('addpro');
        $('.modal-title').text('Létrehozás');
        $('.deleteContent').hide();
        $('.form-horizontal').show();
        $('#pid').val();
        $('#ptitle').val();
        $('#par').val();
        $('#pcat').val();
        $('#pdb').val();
        $('#pcikkszam').val();
        $('#pdescription').val();
        $('#avatar').val();
        $('#prodModal').modal('show');
    });

  $('.modal-footer').on('click', '.addpro', function() {
        
        var prodData = {
                '_token': $('input[name=_token]').val(),
                'pid': $("#pid").val(),
                'pid': $("#pslug").val(),
                'pcat': $("#pcat").val(),
                'ptitle': $('#ptitle').val(),
                'pdb': $("#pdb").val(),
                'pcikkszam': $("#pcikkszam").val(),
                'pdescription': $("#pdescription").val(),
                'par': $("#par").val(),
                'avatar': $("#avatar").val(),
        };

        $.ajax({
            type: 'post',
            url: '/admin/create_products/product_add',
            data: prodData,
            success: function(data) {
             $("<tr class='product" + data.pslug + "'><td>" + data.pcikkszam + "</td><td>" + data.ptitle + "(" + data.pdb + "db)</td><td>" + data.par + " Ft</td><td><a href={!! action('CategoriesController@pedit', " + data.pslug + ") !!}><button class='btn btn-xs'><span class='glyphicon glyphicon-pencil'>Szerkesztés</span></button></a></td></tr>"
              ).prependTo('#storeprod');
            }
        });
    });
spekkionu's avatar

File uploads with ajax is a little bit more involved than what you are doing. $("#avatar").val() will only return the the text that appears in the file upload field which will be the path to the file. What actually needs to be sent is a multipart/form-data request with the form data as one part and the actual content of the selected file as another part.

There are various plugins available to help with this or you could use the native FormData API and FileReader API to read the contents of the file to a Blob.

rob897's avatar

Your form also doesn't have an action.. The form needs to point to an like:

<form class="form-horizontal" method="post" enctype="multipart/form-data" action="/product">

Then your route would have something like

Route::post('product','ProductController@store');

Sorry I missed that you are doing this as an ajax call. I would try out the plugins @spekkionu mentioned above.

Bishwajit's avatar
add an action in your form that can hit your function in controller , and which contains url for your controller

Please or to participate in this conversation.