save all the headaches and just use spatie media library. You can attach media to any model with a simple trait addition
Nov 18, 2017
49
Level 6
Image upload with Pivot Table (foreach loop)
Hello Community,
I am currently working on the Product Creation, so my authenticated business can create products. Therefore I want to provide a multiple Image upload for the product with an Pivot Migration (product_images) to store the images.
Problem
I am facing some problems with my Product Upload Controller, which doesn't find the Pivot column product_image. Plus, I am not sure if the Loop is working.
Would be happy about your expertise.
Image input:
(input type="file" name="images[]" multiple="true" /)
ProductUploadController:
$update = Auth::user()->products()->create([
'business_id' => auth()->user()->id,
'title' => $request->title,
+++
'price' => $request->price,
'availability' => $request->availability,
'product_image' => $request->product_image,
]);
if($request->file('images')){
$business = Auth::user();
$image = $request->file('images');
foreach ($image as $product_image) {
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('uploads/business/products/'. $filename );
Image::make($image)->resize(812, null, function ($constraint){$constraint->aspectRatio();})->save($location);
$product_image = new Picture;
$business->product_image = $filename;
$business->$product->products()->save($product_image);
$business->save();
}
}
Pivot Table: product_images:
public function up()
{
Schema :: create ('product_images', function(Blueprint $table){
$table->increments('id');
$table->unsignedInteger('product_id'); //
$table->string('product_image')->default('productdefault.jpg');
$table->timestamps();
});
}
Product.php Model:
protected $fillable = [
'title',
+++
'availability',
'product_image',
];
public function business()
{
return $this->belongsTo(Business::class, 'business_id');
}
public function images()
{
return $this->hasMany(Picture::class);
}
Picture.php Model
protected $table = 'product_images';
protected $fillable = [
'product_image',
];
public function products()
{
return $this->belongsTo(Product::class);
}
}
Error: Cant find the product_image Pivot column
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'product_image' in 'field list' (SQL: insert into `products` (`title`, `price`, `availability`, `product_image`, `business_id`) values (MM, 09, MM, , 1))
Thank you
Please or to participate in this conversation.