store uploaded images into database laravel 8

  api, file-upload, laravel, php

i have a product and i want it to have multiple file, so i made a oneToMany relation between product and images model.
i was able to upload image successfully

    public function uploadFile(Request $request)
    {
        if($request->hasFile('images'))
        {
            foreach($request->file('images') as $file)
                $file->store('public/images/'. $file->getClientOriginalName());
        }
        return $request->file('images');
    }

now images are storage into storage/public/~ i want to them them to database
Here is my store function in ProductController

public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'price' => 'required|numeric',
            'description' => 'required',
            'category' => 'required',
            'attribute' => 'required',
            'stocks' => 'required|numeric',
            //'discounts' => 'required|numeric'
        ]);

        $product = Product::create($request->only('name','price','description', 'tag', 'category', 'attribute'));
        
        $product->stocks()->create([
            'quantity' => $request->stocks,
            'product_id' => $product->id
        ]);

        $product->discounts()->create([
            //'discount' => $request->discounts,
            'product_id' => $product->id
        ]);

/*
foreach( $request->file('images') as $file)
            {
                $product->images()->create([
                    'product_id' => $product->id,
                    'file_path'  => $file->hashName()
                ]);
            }
*/

}

what should i add to it so i be able to store image into the table

update

images table schema

Schema::create('images', function (Blueprint $table) {
            $table->id();
            $table->string('file_path');
            $table->timestamps();
            $table->foreignId('product_id')->constrained('products')->onUpdata('cascade')->onDelete('cascade');
        });

product table schema

Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->double('price');
            $table->string('category');
            $table->string('attribute');
            $table->text('description');
            $table->string('tag');
            $table->timestamps();
        });

Source: Laravel

Leave a Reply