php - Laravel 8 在 null 上调用成员函数 extension()

标签 php laravel eloquent laravel-8 laravel-migrations

在将配置文件夹中的文件路径更改为 public 并正确设置模型后,我正在尝试在 Laravel 8 中上传图像。我收到了这个回复

Call to a member function extension() on null

我的产品 Controller

 public function store(Request $request)
    {
        $file = $request->file('image');
        $name = Str::random(10);
        $url = Storage::putFileAs('images', $file, $name . '.' . $file->extension());

        $product = Product::create([
            'title' => $request -> input('title'),
            'description' => $request -> input('description'),
            'image' => env('APP_URL') . '/' . $url,
            'price' => $request -> input('price'),
        ]);

        return $product;
    }

我的模型

protected $guarded = ['id'];

迁移

public function up()
   {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('description')->nullable();
            $table->string('image');
            $table->decimal('price');
            $table->timestamps();
        });
    }

请问我做错了什么或做错了什么?

最佳答案

在创建产品之前验证您是否有文件。或者对所有必填字段进行适当的验证。

public function store(Request $request)
    {
        if (!$request->has('image')) {
            return response()->json(['message' => 'Missing file'], 422);
        }
        $file = $request->file('image');
        $name = Str::random(10);
        $url = Storage::putFileAs('images', $file, $name . '.' . $file->extension());

        $product = Product::create([
            'title' => $request -> input('title'),
            'description' => $request -> input('description'),
            'image' => env('APP_URL') . '/' . $url,
            'price' => $request -> input('price'),
        ]);

        return $product;
    }

关于php - Laravel 8 在 null 上调用成员函数 extension(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68390391/

相关文章:

php - 带有大文件的 file_get_contents 和 file_put_contents

php - Laravel: SQLSTATE[HY000] [2054] 服务器请求客户端未知的身份验证方法

ajax - 将 ID 传递给资源 Controller 进行编辑

php - 连接两个表并添加具有相同列id的数据

php - Symfony2 从 Windows(WAMP) => 到 MAC(MAMP)

php - 使用 htaccess 重写/重定向,使单个 PHP 文件可以根据 GET/POST 变量显示数据

php - 将多个var值插入到同一个mysql表中

php - 从营销事件表中,我想删除营销事件,但无法删除..发生以下错误

laravel - 如何在 Laravel Nova 中过滤使用 BelongsTo 字段的选择列表?

php - 如何按多列对 Laravel 查询构建器结果进行排序?