Laravel 8 – How to get product id in ImagesController store function

  laravel, laravel-8, php

Somebody help please, i’m new to laravel and i’m building an ecommerce site. I have products table and images table. Images table has product_id as foreign key. After creating a product successfully, i’m trying to store images for the product. How do i grab the product_id in my ImagesController store function so it can be saved in the database?

Here is my images table

 Schema::create('images', function (Blueprint $table) {
                $table->id();
                $table->unsignedBigInteger('product_id');
                $table->string('imagenames');
                $table->timestamps();
    
                $table->foreign('product_id')->references('id')->on('products');
            });

create.blade.php for the image input

   <form method="post" action="{{ route('images.post') }}" enctype="multipart/form-data">
          @csrf
          <div class="control-group">
              <input type="file" name="filenames[]" class="myfrm form-control" multiple>
          </div>
          <button type="submit" class="btn btn-success" style="margin-top:10px">Upload</button>
    </form>

And here is my ImageController store function

$this->validate($request, [
        'product_id' => 'required|exists:products,id',
        'imagenames' => 'required',
        'imagenames.*' => 'mimes:png,jpeg,jpg'
    ]);
    $product = Product::find($request->product_id);

    if($request->hasfile('imagenames')) {
        foreach($request->image('imagenames') as $image) {
            $imagename= time() . '_' . $image->getClientOriginalName();
            $image->storeAs('public/product_images', $imagename);
            $data[] = $imagename;
        }
    }

    $image= new Uploadfile();
    $image= new Image($data); 
    $image->imagenames= json_encode($data);
    $product->images()->save($image);
    return back()->with('success', 'Your images were successfully uploaded!');

Source: Laravel

Leave a Reply