Search code examples
mysqllaravellaravel-5.3

Invalid argument supplied for foreach() laravel-5.3


i have this on my Controller :

public function store(Request $request)
{
    $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($request->file('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');
}
}

and the browser say : Call to a member function getRealPath() on array i want to store multiple image to database.

this is my blade.php

<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>

should i delete the '[]' on the 'blade' image input ? and 'array' it on controller ? how i do that ?


Solution

  • Change your following code in your controller:

    storage::put('img/report/'.$filename,file_get_contents($request->file('image')->getRealPath()));
    

    to

    storage::put('img/report/'.$filename,file_get_contents($image->getRealPath()));