Search code examples
laravellaravel-storage

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)


Solution

  • 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