Why do you use "image_1", "image_2" etc? You should use array "image[]" as in:
image 1:
<input type="file" name="image[]" id="file" class="custom-file-input" >
image: 2
<input type="file" name="image[]" id="file" class="custom-file-input" >
image: 3
<input type="file" name="image[]" id="file" class="custom-file-input" >
So you can do it like this
if ($request->file('image')){
foreach($request->file('image') as $image) {
$filename = date('YmdHi') . $image->getClientOriginalName();
$image->move(public_path('upload/product'), $filename);
$products[] = $filename;
}
}
Also you should use request validation https://laravel.com/docs/8.x/validation When using request validations, make sure that the requested fields' names are the same as your model's table columns. That way you can easily create/update by passing the validated data, which is an array.
So, using that, you can reduce that big chunk of code to this:
$data = $request->validated();
$product = Product::create($data);
foreach($data['image'] as $image) {
$filename = date('YmdHi') . $image->getClientOriginalName();
$image->move(public_path('upload/product'), $filename);
// Do something with your image here (maybe store it in another table)
}
return redirect()->back();
Some easy way to attach images to a model is to use this package from Spatie https://github.com/spatie/laravel-medialibrary which does everything for you.