简体   繁体   中英

How to display images from storage folder Laravel

I'm trying to retrieve images from storage to the view, but it doesn't show the image, in the console I see this error Failed to load resource: the server responded with a status of 404 (Not Found) . I have tried many solutions, including this but it's still not working.

Controller

 class productController extends Controller
 {

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
 public function index(Request $request)
 {
    $userId = $request->user()->id;
    $products = product::where('admin', $userId)->get();
   return view('admin.product.index',compact('products'));
  }

  public function admin()
  {
   $products=product::all();
   return view('admin.product.index',compact('products'));
   }



  public function show($id)
 {
  $product = ProductsPhoto::findOrFail($id);
  return view('productsPhoto.show', compact('product'));

  }
/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
  public function store(Request $request) 
  { 

    $product = Product::create($request->all());
    foreach ($request->photos as $photo) {
        $filename = $photo->store('photos');
        ProductsPhoto::create([
            'product_id' => $product->id,
            'filename' => $filename
        ]);
      }

ProductsPhotos.php

  class ProductsPhoto extends Model
  {
  protected $fillable = ['product_id', 'filename'];

   public function product()
   {
    return $this->belongsTo('App\Product');
    }

Product.php

protected $table='products';
protected $primaryKey='id';
protected $fillable=['name','price','info','image','stock'];

Blade

 @foreach($products as $product)
     <img src="{{ asset('storage/photos/filename') }}"
 @endforeach

Any help would be appreciated.

Run this artisan command php artisan storage:link . In Blade, use Storage facade below :

 @foreach($products as $product)
     <img src="{{ \Storage::url($products->productPhoto->filename) }}"
 @endforeach

/* UPDATE */

 public function index(Request $request)
 {
    $products = product::where('admin', \Auth::id())->firstOrFail();
   return view('admin.product.index',compact('products'));
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM