codeforfood
codeforfood

Reputation: 439

Laravel having trouble displaying uploaded images

I am attempting to create a simple file upload system for images, and even after hours of googling, I just can't seem to get it working. Users upload images to my website, I store the path of the image in the database, and then I show the images by making the database path the src of an img tag. Seems simple enough, but it still does not work for me. Anyway, here is my code.

//posting upload in controller
//i named images docs

public function postUpload(){

    Input::file('file')->move(base_path() . '/public/uploads');

    $doc = new Doc();
    $doc->title = Input::get('title');
    $doc->caption = Input::get('caption');
    $doc->path = base_path() . '/public/uploads' . Input::file('file')->getClientOriginalName();

    $doc->save();

}

And here is my index view where I display uploaded images:

@extends('layouts.caselistlayout');

@section('content')


@foreach($docs as $doc)
<h1>{{ $doc->title }}</h1>
<h2>{{ $doc->caption}}</h2>
<img src='{{ $doc->path }}'>

@endforeach

@stop

I can provide the code for my upload view, but I don't think it is needed in this situation.

Thanks for the help!

Edit: Forgot to mention that the exact problem is the images aren't displayed. The title and caption are displayed on the index page, but the image is not displayed. I only see the default HTML placeholder for where the image should be.

Edit 2: File ends up in the folder, and I can see the URL in the path column of the database.

Upvotes: 2

Views: 5225

Answers (1)

Anam
Anam

Reputation: 12169

You are saving full physical path to the database which is causing the issue. You actually need a http address. Example:

http://example.com/uploads/img1.jpg

Remove the following line:

  $doc->path = base_path() . '/public/uploads' . Input::file('file')->getClientOriginalName();

Instead, save the following:

  $doc->path = 'uploads/' . Input::file('file')->getClientOriginalName();

and from your view:

<img src='{{ asset($doc->path) }}'>

Upvotes: 4

Related Questions