aleksov's avatar

Upload photo with form

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]);
  });


});

but now when I click to submit form I get error... I try dd($file) and then I just get null so photo is not submited ...

What is a problem here? I just dont see it?

0 likes
5 replies
aleksov's avatar

so when I try to upload photo from form I just get that photo filed is NULL ... why?

jlrdw's avatar

Something along these lines

public function add() {
        //$this->chklog();
        // Session::set('thisadd','z');
        if (isset($_POST['submit'])) {
            echo "made it here";
            $lid = DB::table('dogs')->count();
            $lid = $lid + 1;
            $file = Input::file('ufile');
            $file_name = $file->getClientOriginalName();
            $file_ext = $file->getClientOriginalExtension();

            $fileInfo = pathinfo($file_name);
            $filename = $fileInfo['filename'];




            $newname = $filename . $lid . "." . $file_ext;
            $destinationPath = ROOTDIR . 'upload/imgdogs/';
            //Input::file('ufile')->move($destinationPath, $newname);
            $file->move($destinationPath, $newname);


            $dogpic = Cln::fixValue($newname);
            $dogname = ucfirst(Cln::fixValue($_POST['dogname']));
            $sex = ucfirst($_POST['sex']);
            $comments = Cln::fixValue($_POST['comments']);
            $adopted = (isset($_POST['adopted']) == '1' ? '1' : '0'); ///added
            $lastedit = date("Y-m-d H:i:s");
            echo "adpt=" . $adopted . "aaa";

            if (!isset($error)) {
                $postdata = array(
                    'dogpic' => $dogpic,
                    'dogname' => $dogname,
                    'sex' => $sex,
                    'comments' => $comments,
                    'adopted' => $adopted,
                    'lastedit' => $lastedit
                );

                DB::table('dogs')->insert($postdata);
            }
        }

        $this->layout = 'addtpl';
        return View::make('Dogs/Add')->shares('title', 'Dog Add');
    }


Make sure form is enctype="multipart/form-data

Tweak for laravel, this is another framework using symphony components. Uploading images was recently resolved in a similar post.

1 like
aleksov's avatar

this code work perfect on other project I code but here wont work. I dont know what is a problem? please help

Please or to participate in this conversation.