Upload images and showing them in a view Laravel 5.2

守給你的承諾、 提交于 2019-12-12 04:21:44

问题


I made a function in which I upload images of some products. When I iterate through all my products, I want to show the image too.

The problem is, the image is being uploaded, but I can't present it when i iterate with @foreach. I tried in the controller to get the path but it didn't work.

So far I have done this:

In config/filesystems.php I created a custom storage

'products' => [
        'driver' => 'local',
        'root'   => public_path('/pictures/uploads/products'),
    ],

When I create a new product:

<h1>Create new product</h1>
  {!! Form::open(['route' => 'vendor.allproducts', 'files'=>true]) !!}
  <div class="form-group">
     {!! Form::label('Title', 'Title:') !!}
     {!! Form::text('title',null,['class'=>'form-control']) !!}
  </div>
  <div class="form-group">
     {!! Form::label('File', 'File:') !!}
     {!! Form::file('image') !!}
  </div>

When i iterate through my products info:

@foreach ($products as $product)
    <tr> 
      .
      .

       <td><img src="{{ $product->imagePath }}"></td>
     </tr>
 @endforeach

And in Controller:

public function store(){
    $product = Request::all();
    $file = Request::file('image');
    $extension = $file->getClientOriginalExtension();
    Storage::disk('products')->put($file->getFilename().'.'.$extension,  File::get($file));
    //$product->imagePath = Input::file('image')->getRealPath();
    Auth::user()->products()->create($product);
    return redirect()->route('allproducts');
}

回答1:


Your Store method will be

if(input::hasfile("image")){
        $files = Input::file('image');
        $name = time()."_". $files->getClientOriginalName();
        $image = $files->move(public_path().'/image' , $name);
        $imagefile->image=$name;
    }
         $imagefile->save();

And your view should be as

<td><img src="{{URL::to('/image/' . $product->image)}}"></td>


来源:https://stackoverflow.com/questions/41671373/upload-images-and-showing-them-in-a-view-laravel-5-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!