0
votes

I've tried displaying an image with laravel using a Query-- The images are stored in the storage directory and a symlink with "public" has already been established.

I have tried using: src="{{storage_path('app/public/'.$post->post_image)}}"

src="{{ asset('storage/'.$post->post_image) }}"

src="{{$post->post_image}}"

Testing, I discovered I could use a static path in order to succesfully display the imaage like so:

src="{{ asset('storage/images/image_name.jpeg')}}"

However, this is not what I'm looking for.

The query {{$post->post_image}} returns the following:

127.0.0.1:8000/images/image_name.jpeg

EDIT: If I go edit the database and add "storage/" before the url of the image, then I can use src="{{asset($post->post_image)}}" to display it.

As mentioned before, I already tried src="{{asset('storage/' . $post->post_image)}} without altering the database.

4
You can use str_replace() or preg_replace() to change 127.0.0.1:8000 into storage. - jstarnate
This didnt work, after doing this nothing happened. - RRios
What does the post_image look like in the database? - thefabdev
images/file_name.jpg - RRios
@RRios That's weird. 127.0.0.1:8000 should have access to your public folder. - jstarnate

4 Answers

0
votes

You must save the relative path of the image, after this, you can access as follows:

src="{{ asset('storage/'. $post->post_image )}}"

for more info: docs

0
votes

Only store the image name in your db.

Don't add the path.

You can have a static method in that model that return the path as a string like (return "images/app";)

You can have another method that return a image_url Which is going to be the path + image name

0
votes

I believe Storage::url could help here.

In your Post model, you can define a url helper like so:

public function url()
{
    return Storage::url($this->post_image);
}

Don't forget to import the Storage facade.

use Illuminate\Support\Facades\Storage;

And then retrieve image like so:

{{ $post->url() }}

Also ensure you have a symbolic link created:

php artisan storage:link

UPDATED

In .env add the below:

FILESYSTEM_DRIVER=public

It changes the default FILESYSTEM_DRIVER to public in config/filesystems.php which means it now uses the below config in the same file

'public' => [
     'driver' => 'local',
     'root' => storage_path('app/public'),
     'url' => env('APP_URL').'/storage',
     'visibility' => 'public',
],

Then run the command php artisan config:cache

https://laravel.com/docs/7.x/filesystem#file-urls

0
votes

Thank you all for your contribution, here's how I fixed it using contributions from jstarnate & Abiola:

I created a url helper and properly formatted using str_replace like so:

    public function url()
{
    return str_replace("http://localhost/storage/http://127.0.0.1:8000/","http://127.0.0.1:8000/storage/",Storage::url($this->post_image));
}