Code Lover
Code Lover

Reputation: 8378

Laravel 7 - not getting storage image path correctly

I am unable to fetch the correct image URL to display in view using the asset. The generated URL required storage which is missing in it when I use the asset function and I have to manually add storage in the path like asset('storage/' . $post->image)

I don't understand why the Laravel doesn't add storage automatically?

symlink storage

I have created a symlink of storage folder using the following command

php artisan storage:link

Question:
What I am looking for is the storage folder should be dynamically added to the path so I have to pass only $post->image.

Controller

public function store(PostRequest $request)
{
    // upload the image to storage
    $image = $request->image->store('posts', 'public');

    // create the post
    Post::create([
        'title'       => $request->title,
        'description' => $request->description,
        'content'     => $request->content,
        'image'       => $image,
    ]);

    // redirect with flash message
    return redirect(route('posts.index'))->with('success', 'Post is created');

}

DB image Column Stored Path

posts/ibexiCvUvbPKxzOLSMHQKPpDq7eZXrFA0stBoPfw.jpeg

View

<tbody>
@foreach($posts as $post)
    <tr>
        <td>
            <img src="{{asset($post->image)}}"  width="60" height="60" alt="">
        </td>
        <td>{{ $post->title }}</td>
    </tr>
@endforeach
</tbody>

Storage Path

enter image description here

HTML Source

enter image description here

As you can see in the above references to get the correct URL I have to add storage into asset('storage/'. $post->image)

Upvotes: 1

Views: 4265

Answers (2)

Mohammad Reza
Mohammad Reza

Reputation: 46

another way that can be helpful is using ASSET_URL in your .env file such as:

APP_URL=http://localhost:8000
ASSET_URL = http://localhost:8000/storage

I appended 'storage' on my APP_URL to change default patch of asset helper function, then you can use asset function into your view such as this:

 <img src="{{asset($post->image)}}"  width="60" height="60" alt="">

I hope this way can help you.

Upvotes: 0

Kamlesh Paul
Kamlesh Paul

Reputation: 12401

use Storage::url() function

<tbody>
@foreach($posts as $post)
    <tr>
        <td>
            <img src="{{ Storage::url($post->image)}}"  width="60" height="60" alt="">
        </td>
        <td>{{ $post->title }}</td>
    </tr>
@endforeach
</tbody>

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

Upvotes: 4

Related Questions