Thursday, March 2, 2017

Upload and retrieve image in Laravel

I need to save the image for an avatar.

Can anyone give me a simple code to save and retrieve image?

I need to:

  • Save image in folder
  • Save image name in DB
  • Finally retrieve on image tag; I have to do it by Query Builder

Form:

 <form action="" method="post" role="form" multiple>
        
        <legend>Form Title</legend>

        <div class="form-group">
            <label for="">Your Image</label>
            <input type="file" name="avatar">
        </div>
        <button type="submit" class="btn btn-primary">save</button>
        <a href="/" class="btn btn-primary">back</a>
     </form>
            <img name="youravatar" src="">
        </div>

Route:

Route::get('pic','avatarController@picshow');

Route::post('pic','avatarController@pic');

Controller:

I have the avatarController, but it is empty because I don't know what to do.

Database:

Table name: avatar
Fields: name id, imgsrc, created_at, Updated_at

Other:

I found this code but I can't find out anything:

 if ($request->hasFile('avatar')) {
      $file = array('avatar' => Input::file('avatar'));
      $destinationPath = '/'; // upload path
      $extension = Input::file('avatar')->getClientOriginalExtension();
      $fileName = rand(11111,99999).'.'.$extension; // renaming image
      Input::file('avatar')->move($destinationPath, $fileName);
  }



via siros

Advertisement