如何在一个表中插入多个图像?

时间:2019-10-23 07:39:27

标签: laravel-5

如何在表格中插入多张图像?

Controller

    public function save(Request $request)
   {
    $images = new Image;
    $input = $request->file("image");
    if($files=$request->file('image')){
    foreach($files as $file){
        $name=$file->getClientOriginalName();
        $file->move(public_path("/images/"),$name);
        $images[]=$name;
        $images->Image         =  $input->getClientOriginalName();
    }
}
  $images->save();
  $image = Image::find($request->id);
  return Redirect::to("image")->withSuccess('Great! Image has been successfully uploaded.');
}

我希望将图像插入数据库,错误是没有消息

2 个答案:

答案 0 :(得分:0)

我认为最好使用mass assignment将图像名称插入数据库。代码将如下所示:

public function save(Request $request)
{
    $images = new Image;

    if ($files = $request->file('image')) {
        foreach ($files as $file) {
            $name = $file->getClientOriginalName();
            $file->move(public_path("/images/"),$name);
            $images->create(['Image' => $file]);
        }
    }

    return Redirect::to("image")->withSuccess('Great! Image has been successfully uploaded.');
}

必须在每个循环中插入它,如果使用model属性,则每次循环设置图像名称时它都会改变。

答案 1 :(得分:0)

 public function create(Request $request)
{
    $rules = array(
        'gallery_album_id'=>  'required',
         'image' => 'required',
         'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'

    );

$input=$request->all();
$image=array();
if($files=$request->file('image')){
    foreach($files as $file){
        $name=$file->getClientOriginalName();
        $file->move('images',$name);
        $image=$name;

         gallery::insert( [
    'image'=>  $image,
    'gallery_album_id' =>$input['gallery_album_name']
]);
    }

    }
   return redirect()->route('gallery')->withStatus(__('Album successfully added.'));
}