osherdo's avatar

Attach Uploaded Image To A User

I am uploading image to the server using Dropzone.js. I want to associate the uploaded image to a user . So basically this is a one-to-one realtionship between a user and his profile image.

How can I associate the image with a user?

I have also 2 tables : users and profile_images .I have also created a pivot table with 2 columns : user,image_path . Right now this is the code I have on the view to upload the images (including dropzone.js code). view:


<div class="container">
                <!-- <div class="dropzone" id="dropzoneFileUpload">
                </div> -->
                <form id="dropzoneFileUpload" method="post" action="{{action('DropzoneController@uploadFiles')}}" class="dropzone">
                  <div class="fallback">
                    <input name="file" type="file" />
                    <!-- <input type="hidden" name="_token" value="{{Session::getToken()}}"> -->
                  </div>
                </form>
            </div>

<script type="text/javascript">
                 Dropzone.options.dropzoneFileUpload = {
                    paramName: "file", // The name that will be used to transfer the file
                    maxFilesize: 2, // MB
                    maxFiles: 1,
                    addRemoveLinks: true,
                    init: function(){
                      this.on("success", function(file,resp){
                        if(resp=="success"){
                          alert("Image uploaded successfully");
                        }
                        else {
                          alert("Faild to upload image! Try again");
                        }
                      });
                    }
                  };
             </script>

Controller:

public function index()
{
  return view('dropzone_demo');
}

public function uploadFiles()
{

  $message="Profile Image Created";
  $input = Input::all();

  $rules = array(
      'file' => 'image|max:3000',
  );

  $validation = Validator::make($input, $rules);

  if ($validation->fails()) {
      return Response::make($validation->errors->first(), 400);
  }

  $destinationPath = 'uploads'; // upload path: public/uploads
  $extension = Input::file('file')->getClientOriginalExtension(); // getting file extension
  $fileName = rand(11111, 99999) . '.' . $extension; // renameing image
  $upload_success = Input::file('file')->move($destinationPath, $fileName); // uploading file to given path

  if ($upload_success) {
      return Response::json('success', 200);
  } else {
      return Response::json('error', 400);
  }

}

EDIT: I am trying to insert the uploaded image path to the profile_images table. This is still experimental code, and I have to know yet to associate the image with the authenticated user:


public function __construct()
{
  $user=Auth::user();

}

public function associate()
{
  if(!isset($this->user->id->profile_image))
    {
    echo "no image profile has been uploaded";
    }
  else
    {
      // I need to attach the uploaded image to the authenticated user.
         $profile_image = new AppProfileImage; // Creating a new instance of the model.
         $profile_image->profile_images = $user->id;
         $profile_image->profile_image=
      
    }
}

Question is : how do I process the image that I have uploaded to be set as a profile image of the user?

Would appreciate your suggestions, thanks.

0 likes
6 replies
kobear's avatar

After you save the image, just set the foreign key in Users table to the primary key in the profile_image table.

For instance:

in User Model:

public function profileImage() 
{
    return $this->hasOne('App\ProfileImage', 'id');
}

In ProfileImage model:

public function user() 
{
    return $this->belongsTo('App\User');
}

public function getPathAttribute()
{
    return $this->filePath;   // or however you are storing your full path
}

Then when you display your profile image:

<img src="{{ $user->profileImage->path }}" />
2 likes
osherdo's avatar

@kobear thanks. Right now this is my upload path (declared in the controller):

  $destinationPath = 'uploads';  // upload path: public/uploads

although I am not sure this code will help me to get the path I need:

  public function getPathAttribute()
{
   $destinationPath = 'uploads';
    return $destinationPath;   
}

I am not sure yet how to catch the uploaded image for the js code, and then attach it to a user.

This is my current view code:

  <div class="container">
                <div class="dropzone" id="dropzoneFileUpload">
                </div>
                <button type="button" id="uploadPhoto">Upload Photo</button>
              
            </div>


          <script type="text/javascript">
        
                Dropzone.autoDiscover = false;
                jQuery(document).ready(function(){



                   var myDropzone = new Dropzone("div#dropzoneFileUpload", {
                       url: "{{action('DropzoneController@uploadFiles')}}",
                       maxFilesize: 2, // MB
                           maxFiles: 1,
                           addRemoveLinks: true,
                       autoProcessQueue:false,
                       params: {
                          _token: "{{csrf_token()}}"
                        },

                   });

                     myDropzone.on("success", function(file,resp){
                       if(resp=="success"){
                         alert("Image uploaded successfully");
                       }
                       else {
                         alert("Faild to upload image! Try again");
                       }
                     });


                    jQuery("button#uploadPhoto").click(function(){
                      myDropzone.processQueue();
                    });
                });
             </script>

Thanks.

miigaa's avatar
$this->user->uploadProfileImage($request->file('image'));
public function uploadProfileImage(UploadedFile $file)
{
    $name = time() . $file->getClientOriginalName();
    
    $file->move(self::PROFILE_IMAGES_DIR, $name);

    $this->profile_image = self::PROFILE_IMAGES_DIR . '/' . $name;

    return $this;
}
1 like
osherdo's avatar

@selmonal thanks. I am wondering where to place this code? should I place it on the top of the controller where the upload is processed?

$this->user->uploadProfileImage($request->file('image'));

This is my current controller code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use Input;
use Validator;
use Response;

class DropzoneController extends Controller
{

  public function index()
{
  return view('dropzone_demo');
}

public function uploadFiles()
{

  $get_uploaded_image=$this->user->uploadProfileImage($request->file('image'));
  $input = Input::all();

  $rules = array(
      'file' => 'image|max:3000',
  );

  $validation = Validator::make($input, $rules);

  if ($validation->fails()) {
      return Response::make($validation->errors->first(), 400);
  }

  $destinationPath = 'uploads'; // upload path: public/uploads
  $extension = Input::file('file')->getClientOriginalExtension(); // getting file extension
  $fileName = mt_rand(11111, 99999) . '.' . $extension; // renameing image
  $upload_success = Input::file('file')->move($destinationPath, $fileName); // uploading file to given path

  if ($upload_success) {
      return Response::json('success', 200);
  } else {
      return Response::json('error', 400);
  }

}

public function uploadProfileImage(UploadedFile $file)
{
    $name = time() . $file->getClientOriginalName();

    $file->move(self::PROFILE_IMAGES_DIR, $name);

    $this->profile_image = self::PROFILE_IMAGES_DIR . '/' . $name;

    return $this;
}

}
miigaa's avatar

Sorry. I was too lazy

First one should be in your ProfileController@updateProfileImage

public function updateProfileImage(Request $request)
{
    // Validate the uploading image here.
    
    $this->user->uploadNewProfileImage($request->file('image'));

    // Return a redirector, fire events or do something here.
}

Last one should be in your User model.

const PROFILE_IMAGES_DIR = 'profile_images';

public function profileImages() 
{
    return $this->hasMany('App\ProfileImage', 'id');
}

public function uploadNewProfileImage(UploadedFile $file)
{
    $name = time() . $file->getClientOriginalName();
    
    $file->move(self::PROFILE_IMAGES_DIR, $name);

    $this->profile_image_path = self::PROFILE_IMAGES_DIR . '/' . $name;

    $this->save();

    $this->profileImages()->save(new ProfileImage(['path' => $this->profile_image_path]));
}

Notice that the profileImages relation should be hasMant. Because the user has many old profile images.

Use your profile image in your view like this:

<img src="{{ asset($user->profile_image_path) }}" />

Or display all of your profile images

@foreach($user->profileImages as $image)
    <img src="{{ asset($image->path) }}" />
@endforeach 

I hope you get my idea!

osherdo's avatar

ok I have uploaded the controller's function that uploads the file to the server to look like this:

public function uploadFiles()
{
/*
  $get_uploaded_image=$this->user->uploadProfileImage($request->file('image'));
  */
  $input = Input::all();

  $rules = array(
      'file' => 'image|max:3000',
  );

  $validation = Validator::make($input, $rules);

  if ($validation->fails()) {
      return Response::make($validation->errors->first(), 400);
  }

  $destinationPath = 'uploads'; // upload path: public/uploads
  $extension = Input::file('file')->getClientOriginalExtension(); // getting file extension
  $fileName = mt_rand(11111, 99999) . '.' . $extension; // renameing image
  $upload_success = Input::file('file')->move($destinationPath, $fileName); // uploading file to given path

  if ($upload_success) {
      return Response::json('success', 200);
  } else {
      return Response::json('error', 400);
  }
  $this->user->uploadNewProfileImage($request->file('image'));
}
  return redirect('hub');

It's not redirecting to the hub view,though.

I have updated the model to a hasMany relationship.

yet it shows like the image is not on server. This is how I try to show the image in the hub view

  <img src="{{ asset($user->profile_image_path) }}" />

User.php model:

const PROFILE_IMAGES_DIR = 'uploads';

    public function profile_image()
    {
      return $this->hasMany('App\ProfileImage');
    }

    public function uploadNewProfileImage(UploadedFile $file)
    {
        $name = time() . $file->getClientOriginalName();

        $file->move(self::PROFILE_IMAGES_DIR, $name);

        $this->profile_image_path = self::PROFILE_IMAGES_DIR . '/' . $name;

        $this->save();

        $this->profileImages()->save(new ProfileImage(['path' => $this->profile_image_path]));
    }

I have changed the directory of image uploads to uploads instead of 'profile_images'.

What do you think's wrong now?

thanks for helping!

Please or to participate in this conversation.