You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 9上传图片后如何将图片文件名/路径正确存入数据库

Laravel 9 图片上传路径未写入数据库问题修复

问题原因

  • 控制器逻辑疏漏:代码中已将图片存储路径赋值给$formFields['image'],但执行Posts::create()时传入的字段数组未包含image字段,是数据库字段为null的核心原因。
  • 表单配置缺失:现有文件上传表单未添加enctype="multipart/form-data"属性,该属性是表单上传文件的必填项,缺失会导致服务端无法正常解析文件数据。
  • 模型配置风险:若Post模型的$fillable批量赋值白名单未加入image字段,即使传入该字段也会被框架拦截,无法写入数据库。

完整修复方案

1. 修正上传表单

给表单标签添加文件上传必填的enctype属性,示例代码如下:

<form method="POST" action="{{ route('posts.store') }}" enctype="multipart/form-data">
    @csrf
    <div class="mb-2">
        <label for="image" class="mb-1">Image</label>
        <input type="file" class="w-100" name="image">
        @error('image')
            <p class="mt-1 text-danger">{{ $message }}</p>
        @enderror
    </div>
    <!-- 其余标题、副标题、内容等表单字段保持原有逻辑即可 -->
</form>

2. 修正控制器存储逻辑

在create方法的传参数组中补充image字段,若需要存储原始文件名可替换存储方法:

if($request->hasFile('image')) {
    // 默认写法:框架自动生成随机文件名,返回相对存储路径 例:img/abc123.jpg
    $imagePath = $request->file('image')->store('img', 'public');

    // 若需要存储原始文件名,使用下方storeAs方法替换,加时间戳前缀避免重名覆盖
    // $originalName = $request->file('image')->getClientOriginalName();
    // $imagePath = $request->file('image')->storeAs('img', time().'_'.$originalName, 'public');
}

Posts::create([
    'title' => $request->post('title'),
    'sub_title' => $request->post('sub_title'),
    'tags' => $request->post('tags'),
    'content' => $request->post('content'),
    'featured' => $request->has('featured'),
    // 补充image字段,无上传时赋值为null
    'image' => $imagePath ?? null,
]);

3. 确认模型批量赋值配置

打开app/Models/Post.php文件,确认$fillable白名单中包含image字段:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = [
        'title',
        'sub_title',
        'tags',
        'content',
        'featured',
        'image', // 必须添加该行,否则批量赋值时会过滤image字段
    ];
}

额外配置

图片存储完成后如果需要前端正常访问,执行以下命令生成存储目录软链:

php artisan storage:link

模板中访问图片的示例代码:

<img src="{{ asset('storage/'.$post->image) }}" alt="">

内容的提问来源于stack exchange,提问作者Parit Sawjani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 09:30:47