Laravel 9中Storage::url($h->name)无法正常工作求助
解决Laravel存储图片无法显示的问题
问题分析
你的Storage::url($h->name)生成的路径无法加载图片,但直接输出$h->name能得到/storage/cars/oJxxg1uYAkl0rNPoaQcVj8ycTbpB34daKEpgVi5l.png,核心原因大概率是路径重复拼接或存储链接未配置。
解决方案
创建存储软链接
Laravel的public磁盘需要将storage/app/public目录链接到public/storage,网页才能访问到存储的文件。执行以下Artisan命令创建链接:php artisan storage:link若之前创建过链接但失效,可先删除
public/storage目录,再重新执行上述命令。修正路径重复问题
Storage::url()方法会自动在路径前添加/storage/,而你的$h->name已经包含/storage/cars/前缀,最终会生成/storage/storage/cars/xxx.png这种错误路径。
解决方式:- 调整数据库中
name字段的存储内容,只保留相对路径(如cars/oJxxg1uYAkl0rNPoaQcVj8ycTbpB34daKEpgVi5l.png)或纯文件名(如oJxxg1uYAkl0rNPoaQcVj8ycTbpB34daKEpgVi5l.png),这样Storage::url($h->name)就能生成正确路径。 - 若不想修改数据库,直接使用
$h->name作为图片src:@php $images = \Illuminate\Support\Facades\DB::table('images')->where('ilan_id',$rs->file)->get(); @endphp @foreach($images as $h) <img id="imageharrik" width="50px" height="50px" class="normal" src="{{$h->name}}"> @endforeach
- 调整数据库中
验证文件系统配置
打开config/filesystems.php,确认public磁盘配置正确:'public' => [ 'driver' => 'local', 'root' => storage_path('app/public'), 'url' => env('APP_URL').'/storage', 'visibility' => 'public', ],确保
root指向storage/app/public,url拼接了正确的应用域名与/storage后缀。
内容的提问来源于stack exchange,提问作者selcukctn
相关产品推荐
相关产品推荐

