laravel不会将多个图像文件名保存到数据库

时间:2016-12-13 01:12:39

标签: php laravel laravel-5.3

所以这是我的sotre控制器

$images = $request->file('image');
$file_count = count($images);
$uploadcount = 0;
$daily = new Report();

foreach($images as $image) {    
    $daily = new Report();    
    $destination ='img/report';
    $filename = $image->getClientOriginalName();
    storage::put('img/report/'.$filename,file_get_contents($image->getRealPath()));        
    $daily->image = $filename;
    $uploadcount ++;        
}
$daily->author = $request->author;
$daily->desc = $request->desc;
// $daily->created_at = Carbon::now();
$daily->save();
if($uploadcount == $file_count){ 
    return redirect('/daily');
}else{
    return redirect('/daily/create');
}

这是我的刀锋:

    <form action="/daily/create" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="_token" value="{{{ csrf_token() }}}">
    {{-- date --}}
    {!! Form::text('date', old('date', Carbon\Carbon::today()->format('d-m-Y')),['class'=>'form-control date-picker']) !!}
    {{-- penulis --}}
    <label for="author">Author :</label>
    <input  name="author" type="text" value="{{ Auth::user()->name }}">
    {{-- textarea --}}
    <label for="desc">Description</label>
    <textarea name="desc" id="" cols="30" rows="10"></textarea>
    {{-- input image --}}
    <div class="file-field input-field">
  <div class="btn">
    <span>File</span>
    <input type="file" name="image[]" multiple>
  </div>
  <div class="file-path-wrapper">
    <input class="file-path validate" type="text" placeholder="Upload one or more files">
  </div>
</div>
<center>
<input type="submit" class="btn">
</center>

    </form>

所有图片都已添加并保存到文件夹中,但我只是获取最后一个图像名称.. 我多次阅读这篇文章how to save multiple images in table using laravel php 并且仍然不知道如何修复它hellppppppp ...

1 个答案:

答案 0 :(得分:1)

这里显而易见的问题是,您只能保存1个数据,因为您没有保存每个数据 foreach循环中的new Report()

你做的是在循环结束后保存它,这是你在foreach循环中创建的唯一保存数据是new Report()

要解决该位置,请放置此代码

$daily->author = $request->author;
$daily->desc = $request->desc;
// $daily->created_at = Carbon::now();
$daily->save();

在foreach循环中

$images = $request->file('image');
$file_count = count($images);
$uploadcount = 0;

foreach($images as $image) {    
    $daily = new Report();    
    $destination ='img/report';
    $filename = $image->getClientOriginalName();
    storage::put('img/report/'.$filename,file_get_contents($image->getRealPath()));        
    $daily->image = $filename;
    $uploadcount ++;

    $daily->author = $request->author;
    $daily->desc = $request->desc;
    // $daily->created_at = Carbon::now();
    $daily->save();     
}
if($uploadcount == $file_count){ 
    return redirect('/daily');
}else{
    return redirect('/daily/create');
}