Ticked's avatar

Laravel 5.2 image upload, correct name on database.

Hi, Can someone help me to understand why the code below saves the photo name on the db as temp/... What I'm doing wrong?

public function store(ConsultantRequest $request)
{
    $photo = $request->file('photo');
    $destinationPath = base_path() . '/public/uploads/images/consultants/';
    $photo->move($destinationPath, $photo->getClientOriginalName());
    $consultant = Consultant::create($request->all());
    return $consultant;
    flash('Your consultant has been created');
    return redirect('content-management-system/consultants');
}
0 likes
8 replies
alanaasmaa's avatar

From series http://laravelcoding.com/blog/laravel-5-beauty-the-10-minute-blog

I use, i dont know if there is any help but here:

  public function uploadFile(UploadFileRequest $request)
  {
    $file = $_FILES['file'];
    $fileName = $request->get('file_name');
    $fileName = $fileName ?: $file['name'];
    $path = str_finish($request->get('folder'), '/') . $fileName;
    $content = File::get($file['tmp_name']);

    $result = $this->manager->saveFile($path, $content);

    if ($result === true) {
      return redirect()
          ->back()
          ->withSuccess("File '$fileName' uploaded.");
    }

    $error = $result ? : "An error occurred uploading file.";
    return redirect()
        ->back()
        ->withErrors([$error]);
  }
2 likes
d3xt3r's avatar

@Ticked whenever a file is uploaded, the server uploads it to the temp directory. you will have to move the file to desired location, get hold of the final location and save it in database.

So

 $consultant = Consultant::create($request->all());

saves the temporary location

jekinney's avatar

Your code file get clien original name will get the file name. Currently pushing request all will not accomplish that result. You have to explicitly set the column.

You can: create($request->all(), ['file_column'=> $photo->getClientOriginalName());

Ticked's avatar

For anyone interested this work for me, please consider my level of coding is novice.

    /**
     * File upload
     *
     * @param ConsultantRequest $request
     * @return static
     */
    private function fileUpload($request)
    {
        $imageTempName = $request->file('photo')->getPathname();
        $imageName = $request->file('photo')->getClientOriginalName();
        $path = base_path() . '/public/uploads/consultants/images/';
        $request->file('photo')->move($path , $imageName);
        DB::table('consultants')
            ->where('photo', $imageTempName)
            ->update(['photo' => $imageName]);
    }
2 likes
Christianus's avatar

@ticked THANK YOU SO MUCH BROTHER :') You save me haha i've been looking for this solution in 2 days

Please or to participate in this conversation.