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

Laravel 9图书CRUD添加封面上传报错,请求排查解决

Laravel图书数据库系统图片上传报错排查与解决

错误根源

报错Argument #1 ($rules) must be of type array, Illuminate\Http\Request given的直接原因是控制器中validate方法的传参错误。

Laravel的$request->validate()方法仅需传入验证规则数组作为参数,无需将$request实例本身作为第一个参数传递。你的代码错误地写成了$request->validate($request, [...]),导致第一个参数传入了Request实例而非规则数组,触发类型匹配错误。

修正后的控制器代码

修改BukuController.php中的store方法:

protected function store(Request $request)
{
    // 修正validate传参,仅传入规则数组
    $request->validate([
        'cover' => 'required|file|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        'nama_buku' => 'required',
        'author' => 'required',
        'terbitan' => 'required',
        'barcode' => 'required',
        'ketersediaan' => 'required',
    ]);

    $input = $request->all();
    if ($cover = $request->file('cover')) {
        $destinationPath = 'cover/';
        $profileImage = date('YmdHis') . "." . $cover->getClientOriginalExtension();
        $cover->move($destinationPath, $profileImage);
        $input['cover'] = $profileImage;
    }

    Buku::create($input);

    return redirect()->route('buku.index')->with('success','Buku has been created successfully.');
}

额外注意事项

  • 确保项目根目录下的public/cover/文件夹存在且具备写入权限,否则图片无法正常存储。
  • 若遵循Laravel最佳实践,建议将图片存储到storage/app/public/cover目录,再通过命令php artisan storage:link创建符号链接到public/storage,便于统一管理文件存储。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 10:05:29