I am trying to send photos and store them from PhotoController as below:
public function create()
{
//
$photos = Photo::all();
return view('upload', compact('photos'));
}
public function store(Request $request)
{
//
$size = $request->file('image')->getSize();
$name = $request->file('image')->getClientOriginalName();
$request->file('image')->storeAs('public/images/', $name);
$photo = new Photo();
$photo->name = $name;
$photo->size = $size;
$photo->save();
return redirect()->back();
}
And I try to display them in an upload blade file under view like this:
<form method="POST" action="upload" enctype="multipart/form-data">
#csrf
<input type="file" name="image">
<input type="submit" name="Upload">
</form>
</hr>
<ul>
#foreach (photos as photo)
<li>
<p>
{{ $photo->name }}
</p>
<img src="{{ asset('storage/images/'. $photo->name) }}">
</li>
#endforeach
</ul>
Laravel shows me the following error at the foreach line:
syntax error, unexpected token ")", expecting "->" or "?->" or "{" or "["
was just looking at your view on the foreach part
try changing this line
#foreach (photos as photo)
to this
#foreach ($photos as $photo)
I think you miss the $ in the blade foreach directive.
#foreach ($photos as $photo)
<li>
<p>
{{ $photo->name }}
</p>
<img src="{{ asset('storage/images/'. $photo->name) }}">
</li>
#endforeach
Related
I have tried to code a cutome view in which i would be able to code an html tag to directly download the file which was uploaded before with voyager admin panel. here is my route
Route::get('/download/{research}',[App\Http\Controllers\ResearchController::class, 'download'])->name('download');
here is the html tag:
Download
help me in the controller bellow
public function download(Research $research)
{
}
I've worked through this question all night long and found out this
helpful.
Then I solved it like this:
Controller
public function home()
{
$researches = Research::all();
foreach ($researches as $research){
$download_links[] = json_decode($research->attachment);
}
$departments = Department::all();
$role_id = \TCG\Voyager\Models\Role::all()->where('name','=','student')->first()->id;
$students = User::all()->where('role_id','=',$role_id);
return view('Research.home', compact('researches','departments','students','download_links'));
}
View
{{ $i=0 }}
#foreach($researches as $research)
<div class="row">
<div class="col-md-10">
<button data-toggle="collapse" data-target="#demo{{ $research->id }}" class="btn border text-start form-control" title="click to read abstract">[ {{ ucwords($research->title) }} ] By: {{ $research->user->name }} #if($research->user->student != null) {{ $research->user->student->last_name }} #else {{ $research->user->employee->last_name }}#endif</button>
</div>
<div class="col">
Download
</div>
</div>
<div id="demo{{ $research->id }}" class="collapse row border">
<div class="col-md-12 ">{!! $research->description !!}</div>
</div>
#endforeach
and now is working properly.
public function download($id) {
$research= Research::where('id', $id)->firstOrFail();
$pathToFile = storage_path('fileName' . $research->file);
return response()->download($pathToFile);
}
Image is not displaying however it is saving in db and folder.
I could not get it where is the problem
apperance.blade.php
<div id="bgimage" class="hovercover text-center">
<img class="img-responsive" src="img/{{$image->image ?? ''}}" style="margin-top: {{$image->position ?? ''}}">
<div class="hover-div">
<form id="hoverform" action="{{url('/employee-appearance')}}" enctype="multipart/form-data" method="post">
{{ csrf_field() }}
<label class="custom-file-upload" title="Change Cover Image" for="file-upload"> <i class="fa fa-file-image-o"></i> Change Cover </label>
<input id="file-upload" name="file" type="file">
</form>
</div>
</div>
<div id="adjimage" class="hovercover1 text-center" style="display: none;">
</div>
imageProcessController
public function upload()
{
$image=DB::table('images')->latest('image','position')->first();
return view('user.employeeforms.appearance',compact('image')) ;
}
public function postupload(Request $request)
{
$file = $request->file('file');
$rules = array('file' => 'required|mimes:png,gif,jpeg,jpg');
$validator = Validator::make(array('file'=> $file), $rules);
if($validator->passes()) {
$image = $file->move( 'img', sprintf('%s-%s.%s', time(), "abc", explode('/', $file->getMimeType())[1]));
$img = new Image;
$img->image = $image->getFilename();
$img->save();
}
}
There may be possibilities that it could be.
But the most likely one is that the symlink has not been set yet!?
php artisan storage:link
If you have already set it, look in the storage/app order where the files are. If they are under storage/app/img then you have to change the link like this:
<img src="img/{{$image->image ?? ''}}"
should be:
<img src="{{ asset('storage/img/' . $image->image ?? "placeholder.jpg" ) }}">
I'm trying to show a book's comments by ISBN (book table's PK) and I get the following error:
Invalid argument supplied for foreach
I'm using Laravel relationship and a foreach to get the records from the following query, in a Helper class:
function getCommentsByISBN($data)
{
foreach (Book::where("ISBN", $data)->get() as $comments) {
return $comments->comments;
}
}
And here's my Book model, comment relationship:
public function comments()
{
return $this->hasMany(Comment::class, "ISBN", "ISBN");
}
And here's the view where I show the comments:
#foreach(getCommentsByISBN(session("isbn")) as $comment)
<div class="form-group">
<h3>
{{ getUserWhoPostedComment($comment->email) }}
</h3>
<p>
{{ $comment->commentary }}
</p>
#if(Session::has("username") && isAdmin(session("username")))
<button type="button" onclick="openModal('{{$comment->commentary}}')"
name="warningButton" class="btn btn-warning" data-toggle="modal"
data-target="#modalWarning">
<i class="fas fa-exclamation-circle"></i>
</button>
#endif
<hr>
<span>
Hace: {{ getTimeWherePostedComment($comment->publicated_at) }}
</span>
</div>
#endforeach
Thanks in advance!
I think you helper returns void because no book was found with that ISBN.
I think it should look like this btw
function getCommentsByISBN($isbn)
{
if ($book = Book::where("ISBN", $isbn)->first()) {
return $book->comments;
}
}
and in your blade your top should look like
#php
$comments = getCommentsByISBN(session("isbn")) ?: [];
#endphp
#foreach($comments as $comment)
<div class="form-group">
/// Rest of the code
Greeting developers,
I was trying to create one database to store images. It stores the URL of that image and the insertion is working fine.
Now I want to display the image stored in the database but it just shows image icon and not display the image. The image is stored in the image folder inside the public folder. I really need a favor. Thanks in advance. Below I attach my code:
Form Controller:
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 has been successfully');
}
public function show()
{
$users = DB::select('select * from forms');
return view('display',['users'=>$users]);
}
Insert page
<form method="post" action="{{url('form')}}" enctype="multipart/form-data">
{{csrf_field()}}
<div class="input-group control-group increment" >
<input type="file" name="filename[]" class="form-control">
<div class="input-group-btn">
<button class="btn btn-success" type="button"><i class="glyphicon glyphicon-plus"></i>Add</button>
</div>
</div>
<div class="clone hide">
<div class="control-group input-group" style="margin-top:10px">
<input type="file" name="filename[]" class="form-control">
<div class="input-group-btn">
<button class="btn btn-danger" type="button"><i class="glyphicon glyphicon-remove"></i> Remove</button>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary" style="margin-top:10px">Submit</button>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
$(".btn-success").click(function(){
var html = $(".clone").html();
$(".increment").after(html);
});
$("body").on("click",".btn-danger",function(){
$(this).parents(".control-group").remove();
});
});
</script>
Display Page:
#foreach ($users as $user)
<img src= url({{url('images/$user->filename')}});}/>
#endforeach
Your are storing multiple filenames as json in filename column in forms table. In blade template you're inserting json in img src instead of single filename. As filenames are stored as json so you need to decode json and run foreach for each filename.
#foreach ($users as $user)
#php $filenames = json_decode($user->filename); #endphp
#foreach ($filenames as $filename)
<img src="{{ url('images/' . $filename) }}"/>
#endforeach
#endforeach
if its json do like this
#foreach ($users as $user)
#php $images = json_decode($user->filename,true); #endphp
#foreach ($images as $image)
<img src="{{ url('images/'.$image) }}"/>
#endforeach
#endforeach
you are encoding the filenames in your controller which is an array so in your blade template you would must decode it first and then loop through it through foreach loop and show it in the img tag. Hope it will help you.
I'm trying to upload 2 images with 2 form fields. My form:
->add('zdjecie', FileType::class, array('label' => 'Zdjecie (img file)'))
->add('zdjecieMIN', FileType::class, array('label' => 'Zdjecie miniatura (img file)'))
Entity:
/**
* #ORM\Column(type="string")
*
* #Assert\NotBlank(message="Dodaj zdjecie miniaturke")
* #Assert\File(mimeTypes={"image/png", "image/jpeg", "image/jpg",})
*/
private $zdjecieMIN;
public function getZdjecieMIN()
{
return $this->zdjecieMIN;
}
public function setZdjecieMIN($zdjecieMIN)
{
$this->zdjecieMIN = $zdjecieMIN;
return $this;
}
/**
* #ORM\Column(type="string")
*
* #Assert\NotBlank(message="Dodaj zdjecie")
* #Assert\File(mimeTypes={"image/png", "image/jpeg", "image/jpg",})
*/
private $zdjecie;
public function getZdjecie()
{
return $this->zdjecie;
}
public function setZdjecie($zdjecie)
{
$this->zdjecie = $zdjecie;
return $this;
}
Controller:
public function newAction(Request $request)
{
$buty = new Buty();
$form = $this->createForm('ShoeShopBundle\Form\ButyType', $buty);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$file = $buty->getZdjecie();
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move(
$this->getParameter('img_directory'),
$fileName
);
$buty->setZdjecie($fileName);
$file2 = $buty->getZdjecieMIN();
$fileName2 = md5(uniqid()).'.'.$file->guessExtension();
$file2->move(
$this->getParameter('img_directory'),
$fileName2
);
$buty->setZdjecieMIN($fileName2);
$em = $this->getDoctrine()->getManager();
$em->persist($buty);
$em->flush();
return $this->redirectToRoute('app_admin_buty_show', array('id' => $buty->getId()));
}
return $this->render('ShoeShopBundle:Admin/Buty:new.html.twig', array(
'buty' => $buty,
'form' => $form->createView(),
));
}
Config:
parameters:
locale: en
img_directory: '%kernel.root_dir%/../web/uploads/img'
Everything was ok when I was using only 1 image upload field but now im getting "The file "C:\xampp\tmp\phpBF79.tmp" does not exist " error, anyone know what's wrong?
Thanks in advance for your help.
Edit: Added my html/twig form
{% extends 'base.html.twig' %}
{% block body %}
<div class="adm-new">
<h2>Dodaj nowy produkt</h2>
{{ form_start(form) }}
<div>
{{ form_errors(form.marka) }}
<div>
<div>
{{ form_label(form.marka) }}:
</div>
</div>
<div>
<div>
{{ form_widget(form.marka) }}
</div>
</div>
</div>
<div>
{{ form_errors(form.model) }}
<div>
<div>
{{ form_label(form.model) }}:
</div>
</div>
<div>
<div>
{{ form_widget(form.model) }}
</div>
</div>
</div>
<div>
{{ form_errors(form.kolor) }}
<div>
<div>
{{ form_label(form.kolor) }}:
</div>
</div>
<div>
<div>
{{ form_widget(form.kolor) }}
</div>
</div>
</div>
<div>
{{ form_errors(form.cena) }}
<div>
<div>
{{ form_label(form.cena) }}:
</div>
</div>
<div>
<div>
{{ form_widget(form.cena) }}
</div>
</div>
</div>
<div>
{{ form_errors(form.rozmiar) }}
<div>
<div>
{{ form_label(form.rozmiar) }}:
</div>
</div>
<div>
<div>
{{ form_widget(form.rozmiar) }}
</div>
</div>
</div>
<div>
{{ form_errors(form.zdjecieMIN) }}
<div>
<div>
{{ form_label(form.zdjecieMIN) }}:
</div>
</div>
<div>
<div>
{{ form_widget(form.zdjecieMIN) }}
</div>
</div>
</div>
<div>
{{ form_errors(form.zdjecie) }}
<div>
<div>
{{ form_label(form.zdjecie) }}:
</div>
</div>
<div>
<div>
{{ form_widget(form.zdjecie) }}
</div>
</div>
</div>
<div><input type="submit" value="Dodaj" /></div>
{{ form_end(form) }}
<ul>
<li>
Powrot do listy produktow
</li>
</ul>
</div>
{% endblock %}
I have a suspicion that uniqid is generating the same filename for both uploads, and that that is the heart of the file-not-found issue you're seeing.
From the PHP docs:
uniqid
Gets a prefixed unique identifier based on the current time in microseconds.
Both calls to uniqid are executed close enough together that based on the time-in-microseconds part of the function, it might assign them both the same name. Therefore, the second one will be "missing" when you go to $file->move it.
Try subbing in mt_rand, for a far lesser likelihood of file name collisions. You can also mitigate this possibility by calling getBasename on the $file, and concatenating that to the string passed to md5.
Like Camerun Hurd suggested it was a problem with uniqid generating the same filename for both files. mt_rand() function gave the same result so I just changed
$file2 = $buty->getZdjecieMIN();
$fileName2 = md5(uniqid()).'.'.$file->guessExtension();
$file2->move(
$this->getParameter('img_directory'),
$fileName2
);
$buty->setZdjecieMIN($fileName2);
in my controller to:
$ext_pos = strrpos($fileName, '.');
$file2 = $buty->getZdjecieMIN();
$fileName2 = substr($fileName, 0, $ext_pos) . '_min' . substr($fileName, $ext_pos);;
$file2->move(
$this->getParameter('img_directory'),
$fileName2
);
$buty->setZdjecieMIN($fileName2);
Thanks Cameron and rodd from #symfony for all the help.
I think it not solve your problem but you check in file2name extension from file not from file2.
If you move file to another place maybe it's problem with guessExtension() on moved file.