aleksov's avatar

Can't upload image with form (strange issue)

I use laravel 5.1 and I need to store photo into folder /images.

I have store function:


public function store(Requests\VoucherRequest $request)
    {

        //$photo= null;
        $file = array('photo' => $request->file('photo'));
        // setting up rules
        dd($request->file('photo'));
        $rules = array('photo' => 'required|image|max:10000'); //mimes:jpeg,bmp,png and for max size max:10000
         // doing the validation, passing post data, rules and the messages
        $validator = Validator::make($file, $rules);
        if ($validator->fails()) {
        // send back to the page with the input data and errors
         return redirect()->back()->withErrors(["photo" => "Photo requirments - format: jpg, jpeg, png | max. size: 1 MB"]);

        }
        else {
    // checking file is valid.
        if ($request->file('photo')->isValid()) {
        $destinationPath = public_path().'/images'; // upload path
        $extension = $request->file('photo')->getClientOriginalExtension(); // getting image extension
        $photo  = str_random(5).'.'.$extension; // renameing image
         $request->file('photo')->move($destinationPath, $photo); // uploading file to given path
         // sending back with message

         }
        else {
      return redirect()->back()->withErrors(["photo" => "Photo requirments - format: jpg, jpeg, png | max. size: 1 MB"]);
        }
        }


        $voucher = new Voucher($request->all());
        //$article['key']= str_random(30);
        $voucher['photo'] = $photo;


        Auth::user()->vouchers()->save($voucher);

        Alert::success('Voucher has beed added!','Good job!')->persistent("Close");



        return redirect('vouchers');
    }

also I have inside create.blade.php:


{!! Form::open(['url'=>'vouchers','files' => 'true']) !!}

                @include('vouchers.form',['submitButtonText'=>'Click to Add New Vocuher'])

                {!! Form::close() !!}

and I have form.blade.php:


<div class="form-group row del hidden">
    <p class="col-md-3 text-right">{!! Form::label('photo','Upload best image of room') !!}</p>
    <div class="col-md-6">
    {!! Form::file('photo', null, ['class'=>'btn btn-info']) !!}
    </div><br>

</div>

<div class="form-group row">
    <div class="col-md-12">
    <div class="output"><h6 class="text-center">Click here to add image</h6>
    <p class="text-center">( Allowed format is: jpg, jpeg, png | max. size: 1 MB )
    <div class="image" class="col-md-3">
      <img id="image" style="width:100%;">
    </div>
    </div>
    </div>

</div>

and js code:


           $(function () {


      $( ".output" ).on( "click", function() {
  $('#photo').trigger('click');
});
    $("#photo").on("change", function (e) {
    var image = document.getElementById('image');
    image.src = URL.createObjectURL(e.target.files[0]);
  });


});

NOW when I pick photo in form and other data then I just get error from controller so "Photo requirments - format: jpg, jpeg, png | max. size: 1 MB" text ... Also I try dd($file) and I get as a result NULL ... why? What is a problem here?

Why I can't upload photo?

0 likes
9 replies
aleksov's avatar

where... i just need answer what is wrong with my code... why i get photo - null when i submit photo

jlrdw's avatar

Probably this public function store(Requests\VoucherRequest $request) Just do one regular for a test.

aleksov's avatar

my VocuherRequest is:


<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class VoucherRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name'=>'required|min:3',
            'description'=>'required',
            'price'=>'required',
            
            
        ];
    }
}
jekinney's avatar

I don't see where the file is put in the input. You have some JavaScript I guess is to preview the image?

aleksov's avatar

becouse of UI I hide with css form but trigger to open on click the desktop WIndows browser to pick image:

$(function () {

  $( ".output" ).on( "click", function() {

$('#photo').trigger('click'); }); $("#photo").on("change", function (e) { var image = document.getElementById('image'); image.src = URL.createObjectURL(e.target.files[0]); });

});

jlrdw's avatar

I am just saying to test things forget all about VocuherRequest and concetrate on getting an image uploaded first, then tie all together.

aleksov's avatar

ok, thanks but I try to upload image but when add dd($request->file('photo')); I got NULL as a result. WHY?

aleksov's avatar

the question now is : WHY this line: {!! Form::open(['url'=>'vouchers','files' => 'true']) !!} dont make form with: enctype="multipart/form-data" ??? WHy there is no enctype ... as you can see I use files => true ...

jekinney's avatar

I don't use the form helpers. But yes your hiding the file input but setting the src on an img tag doesn't set the file input element.

Why not just style the file input instead? Also once JavaScript is involved with a file the file to be uploaded needs to be set as a file object.

http://www.w3schools.com/jsref/dom_obj_fileupload.asp

Please or to participate in this conversation.