Reputation: 655
New to Laravel and feel that I'm missing something important here. I am uploading and saving multiple files to a folder and saving an array of the images names to the database(simple enough). Currently saving the images name in the json_encode()
format so they are formatted like so["kittyTest.jpeg","kitty_2.jpeg","kitty_3.jpeg"]
. So when I try and print them out to the view I get them in the json format and am trying to display them in an array formate or in some way that I can use the filename for the source image. Any help or guidance would be much appreciated.
Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Form;
use DB;
class FormController extends Controller
{
public function index()
{
$images = DB::select('select * from forms');
//dd(json_decode($images[0]->filename));
return view('index', ['images'=> $images]);
}
public function create()
{
return view('create');
}
public function store(Request $request)
{
$this->validate($request, [
'filename' => 'required',
'filename.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
if ($request->hasFile('filename')) {
foreach ($request->file('filename') as $image) {
$name = $image->getClientOriginalName();
$image->move(public_path().'/images/', $name);
$data[] = $name;
}
}
$form = new Form();
$form->filename = json_encode($data);
$form->save();
return back()->with('success', 'Your images have been uploaded');
}
}
View
<body>
<div class="container">
<h3 class="jumbotron">Laravel Multiple File Upload</h3>
<p>Here are the images we have in the database</p>
<ul class="list-group">
@foreach ($images as $image)
<li class="list-group-item">
{{ $image->filename }}
</li>
@endforeach
</ul>
</div>
</body>
Upvotes: 1
Views: 95
Reputation: 4826
<ul class="list-group">
@foreach ($images as $image)
@php $image_array = json_decode($image->filename,true); @endphp
@foreach ($image_array as $img)
<li class="list-group-item">
{{ $img }}
</li>
@endforeach
@endforeach
</ul>
try this and let me know
Upvotes: 2
Reputation: 137
In your controller use array_map to json_decode every image filenames and then use second foreach in your view file.
Controller
public function index()
{
$images = DB::select('select * from forms');
array_map(function($a) {
$a->filename = json_decode($a->filename);
return $a;
}, $images);
return view('index', compact($images)); // you can use compact function here
}
View
<ul class="list-group">
@foreach ($images as $image)
<li class="list-group-item">
@foreach ( $image->filename as $file)
{{ $file }}
@endforeach
</li>
@endforeach
</ul>
Edit: You can also try cast to array, then you dont need to worry about mapping it in your controller file.
Upvotes: 0