Is there a more elegant and shorter way to save bulk results to the database without using the foreach
interaction. The method is already huge and I am trying to break it down into smaller units for easier maintenance.
/**
* Store a newly created resource in storage.
*/
public function store(ProductPostRequest $request)
{
// Product main image
if($request->hasFile('image'))
{
$image = $this->_uploadProductImage($request);
}
$data = [
'name' => $request->input('name'),
'model' => $request->input('model'),
'code' => $request->input('code'),
'slug' => $request->input('slug'),
'image' => $image ?? '',
'manufacturer_id' => $request->input('manufacturer_id'),
'price' => $request->input('price'),
'discount_price' => $request->input('discount_price'),
'status' => $request->input('status'),
'description' => $request->input('description'),
'short_description' => $request->input('short_description'),
'meta_title' => $request->input('meta_title'),
'meta_description' => $request->input('meta_description'),
'stock_status' => $request->input('stock_status'),
'featured' => $request->input('featured')
];
$product = Product::create($data);
$product->categories()->attach($request->input('categories'));
// Save product gallery images
if($request->hasFile('gallery'))
{
$path = config('ecommerce.product_upload_dir').'/'.Str::slug($request->input('name'), '-');
foreach ($request->file('gallery') as $item) {
$product->gallery()->create([
'image' => $path.'/'.$item->getClientOriginalName(),
]);
}
}
return redirect()->route('product.index')
->with('success', 'The product'. $product->name .' has been successfully created.');
}
This part i want to make simpler
foreach ($request->file('gallery') as $item) {
$product->gallery()->create([
'image' => $path.'/'.$item->getClientOriginalName(),
]);
}
Does Laravel have a method that will do this?