【问题标题】:Laravel 7 - not getting storage image path correctlyLaravel 7 - 没有正确获取存储图像路径
【发布时间】:2020-04-02 06:25:44
【问题描述】:

我无法使用资产获取正确的图像 URL 以显示在视图中。生成的 URL 需要 storage,当我使用 asset 函数时,其中缺少该 URL,我必须在路径中手动添加 storage,例如 asset('storage/' . $post->image)

我不明白为什么 Laravel 不自动添加storage

符号链接存储

我使用以下命令创建了存储文件夹的符号链接

php artisan storage:link

问题:
我正在寻找的是应该将storage 文件夹动态添加到路径中,因此我只需要传递$post->image

控制器

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 列存储路径

posts/ibexiCvUvbPKxzOLSMHQKPpDq7eZXrFA0stBoPfw.jpeg

查看

<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>

存储路径

HTML 源代码

正如您在上述参考资料中看到的那样,为了获得正确的 URL,我必须将 storage 添加到 asset('storage/'. $post-&gt;image)

【问题讨论】:

标签: laravel laravel-storage


【解决方案1】:

使用Storage::url()函数

<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>

参考链接https://laravel.com/docs/7.x/filesystem#file-urls

【讨论】:

    【解决方案2】:

    另一种有用的方法是在您的 .env 文件中使用 ASSET_URL,例如:

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

    我在我的 APP_URL 上添加了“storage”来更改资产辅助函数的默认补丁,然后您可以在视图中使用资产函数,例如:

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

    希望这种方式可以帮到你。

    【讨论】:

      猜你喜欢
      • 2021-06-07
      • 2016-10-05
      • 1970-01-01
      • 1970-01-01
      • 2017-02-11
      • 2019-03-17
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      相关资源
      最近更新 更多