I'm trying to save multiple images of products in the database. I created the images table and set up a relationship with the products table.
Controller
public function store(Request $request)
{
$formInput = $request->all();
$image = array();
if ($files = $request->file('image')) {
foreach ($files as $file) {
$name = $file->getClientOriginalName();
$file->move('images', $name);
$image[] = $name;
}
}
//dd($formInput);
Product::create(array_merge($formInput,
[
// 'product_id'=>$product->id,
'image' => 'what to put here',
'seller_id' => Auth::user()->id,
]));
return redirect()->back();
}
Image Model
class Image extends Model
{
protected $table = 'images';
protected $fillable = ['product_id', 'image'];
public function product()
{
return $this->belongsTo('App\Product', 'product_id');
}
}
Product Model
class product extends Model
{
protected $table = 'products';
protected $primaryKey = 'id';
protected $fillable = ['seller_id', 'pro_name', 'pro_price', 'pro_info', 'stock', 'category_id'];
public function images()
{
return $this->hasMany('App\Image', 'product_id');
}
}
When I dd($formInput)
I see all the details, including images, but how do I submit them to the database? Images to images table and products details to the products table.
You should use insert images in images table using Image::create() and in images table you should make a foreign key(product_id) to product's id. There will be no entry in Products table regarding images. Just create the products with normal fields and not including any image details.
public function store(Request $request)
{
$formInput = $request->all();
$image = array();
if ($files = $request->file('image')) {
foreach ($files as $file) {
$name = $file->getClientOriginalName();
$file->move('images', $name);
$image[] = $name;
}
}
//dd($formInput);
Image::createMany([
'product_id': //'value of id': Same for all images of this product
],[...])
Product::create(array_merge($formInput,
[
// 'product_id'=>$product->id,
// 'image' => 'what to put here',
'seller_id' => Auth::user()->id,
//Other Fields' details...
]));
return redirect()->back();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.