Reputation: 602
How to display multiple images in my products.blade.php
Here is my ProductsController
:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Product;
class ProductsController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$products = Product::all();
return view('products')->with('products', $products);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('createprod');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$input=$request->all();
$images=array();
if($files=$request->file('images')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move('storage/image',$name);
$images[]=$name;
}
}
/*Insert your data*/
Product::insert( [
'images'=> implode("|",$images),
'title' =>$input['title'],
//you can put other insertion here
]);
return redirect('/products');
}
}
And this is my products.blade.php
:
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">All products
<a href="/products/create" class="btn btn-primary" style="margin-left: 70%">New product +</a></div>
<hr>
<div class="card-body">
@foreach($products as $product)
<h2>{{$product->title}}</h2>
<hr>
<img style="width:100%" src="/storage/image/{{$product->images}}">
<br>
<hr>
@endforeach
<small><?php echo now() ?></small>
</div>
</div>
</div>
</div>
</div>
@endsection
When I upload just one image it shows on my blade but when I try to upload more it shows broken image icon. I hope somebody will help!
Upvotes: 0
Views: 961
Reputation: 129
If $product->images is held as a string imploded with |, when you have more than one image you need to explode these (on the controller/model level or on blade's) and loop over them in the blade template.
So instead <img style="width:100%" src="/storage/image/{{$product->images}}">
you would need something like:
@foreach (explode('|', $product->images) as $image)
<img style="width:100%" src="/storage/image/{{$image}}">
@endforeach
TIP If I were you, I would read about Laravel Eloquent Mutators. I think they would make your life much easier. You would have a mutator that would implode your pictures on the fly when you create/save a model and explode when you retrive it from the database.
Upvotes: 1