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="hidden" name="product_id" value="{{ $product_id }}"/>
<input type="file" name="filenames[]" hljs-string">" multiple/>
</div>
<button type="submit" hljs-string">" 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 Image();
$image->imagenames= json_encode($data);
$image->save($image);
return back()->with('success', 'Your images were successfully uploaded!');
CodePudding user response:
when you prepare $image for storing just give it product_id
$image= new Uploadfile();
$image= new File($data);
$image->imagenames= json_encode($data);
$image->product_id= $request->input('product_id');
CodePudding user response:
You should add product_id
to object
$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 Image();
$image->imagenames= json_encode($data);
$image->product_id = $request->product_id ;
$image->save($image);
return back()->with('success', 'Your images were successfully uploaded!');