3

I am trying to upload an image in Laravel 8, after changing the file path to public in the config folder and setting up the Model properly. I am getting this response

Call to a member function extension() on null

My Product 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;
    }

My model

protected $guarded = ['id'];

Migration

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();
        });
    }

What have I done wrong or what am I not doing right please?

STA
  • 30,729
  • 8
  • 45
  • 59
Adetola Aremu
  • 63
  • 1
  • 2
  • 6

1 Answers1

4

Verify that you have a file before creating the product. Or do a proper validation of all required fields.

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;
    }
N69S
  • 16,110
  • 3
  • 22
  • 36