Display image from the url save in database - php

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.

Related

Storing and display image in blade file

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

How can a voyager link for downloading the file uploaded by voyager be defined in a cutome view?

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 although saving in DB and folder Laravel

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" ) }}">

laravel 7 - add new images on existing tables

I was successful uploading multiple images while inserting a new record. I used two models Car and caralbum and made a join. However, I was trying to create an option to add more images on current list but failed to do so. my codes are-
controller to add new record with multiple images
$car = new Car;
.......
.......
$car->save();
if (count($request->car_image) > 0) {
foreach ($request->car_image as $image) {
........
........
Image::make($image)->save($location);
$caralbum = new caralbum;
$caralbum->car_id = $car->id;
$caralbum->image_name = $image_name;
$caralbum->image_location = $location;
$caralbum->save();
}
}
controller to add additional images
$car = Car::find($id);
if (count($request->car_image) > 0) {
foreach ($request->car_image as $image) {
....
....
Image::make($image)->save($location);
$caralbum = new caralbum;
$caralbum->car_id = $car->id;
$caralbum->image_name = $image_name;
$caralbum->image_location = $location;
$caralbum->save();
blade to add new record with multiple images
<input type="file" name="car_image[]" multiple>
blade to add additional images
<input type="file" name="car_image[]" multiple>
<a class="btn btn-success" href="{{ url('car_store_images/'.$cars->id) }}">
Add Images
</a>
I have found one problem. on the index blade where I am displaying the images the image class was not named as array. After adding [] after it, it is working now.
#foreach ($cars->join_caralbum as $image)
<div class="card" >
<img class="card-img-top" name="car_image[]" src="{{asset($image->image_location)}}" style ="height:90px; width:120px;" >
<a class="btn btn-danger" href="{{ url('car_destroy_image/'.$image->id) }}"
onclick="return confirm('Are you sure you want to delete all images for this car?')"><i class="fas fa-trash fa-xs"></i></a>
</div>
#endforeach

Laravel how to upload an image to a database and show it in view

So i was making a form that consists of three field, the title, thumbnail, and textarea(with texteditor) and it seems that it upload the image just fine since i notice that there is images that i had uploaded in my /public/image folder after i submit the form, but when i check the database the thumbnail field showed not the name of the file in the /public/image folder like 20190713125534.jpg but
C:\xampp\tmp\phpC18A.tmp
im confused i thought it doesn't upload the image at all, but as i explained earlier it does, so my question is how do i change the value of thumbnail field with the filename and how do i show the image in my view ?
this is my Blogcontroller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Blog;
use Validator,Redirect,Response,File;
class BlogController extends Controller
{
public function index()
{
$blogs = Blog::get();
return view('post.post_textarea',[
'blogs' => $blogs
]);
}
public function store(Request $request)
{
Blog::create([
'name' => $request->name,
'message' => $request->message,
'thumbnail' => $request->thumbnail,
]);
if ($files = $request->file('thumbnail')) {
$destinationPath = 'public/image/'; // upload path
$profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profileImage);
$insert['thumbnail'] = "$profileImage";
}
return redirect()->back();
}
public function getFullPost($blog_id) {
$blogs = Blog::where('id', '=', $blog_id)->get();
return view('post.read')->with(compact('blogs'));
}
}
this is my view for the form
<form enctype="multipart/form-data" method="POST">
{{csrf_field()}}
<div class="form-group">
<h4 style="color: black;" >Judul</h4>
<br>
<input type="text" class="form-control" name="name">
</div>
<div class="form-group">
<h4 style="color: black;" >Thumbnail</h4>
<br>
<input type="file" name="thumbnail">
</div>
<div class="form-group">
<h4 style="color: black;" >Isi</h4>
<br>
<textarea class="form-control" name="message" id="" rows="10"></textarea>
</div>
<div class="form-group">
<button class="pull-right site-btn" type="submit" >Upload<img src="../public/asset/img/icons/double-arrow.png" alt="#"/></button>
</div>
</form>
and this is my view to display the data from database
#foreach ($blogs as $blog)
<div class="blog-item">
<div class="blog-thumb">
<img src="asset/img/blog/1.jpg" alt=""> ->this is where i was supposed to fetch the image
</div>
<div class="blog-text text-box text-white">
<div class="top-meta">{{ Carbon\Carbon::parse($blog->created_at)->format('d-m-Y') }} / di Rakitan</div>
<h3>{{ $blog->name }}</h3>
<p>{!! \Illuminate\Support\Str::words($blog->message, 30, '...') !!}</p>
Lanjutkan Baca <img src="asset/img/icons/double-arrow.png" alt="#"/>
</div>
</div>
#endforeach
try to add this in controller
$blog = new Blog;
$blog->name = $request->name;
$blog->message = $request->message;
if($request->hasFile('thumbnail')) {
$file = Input::file('thumbnail');
//getting timestamp
$timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
$name = $timestamp. '-' .$file->getClientOriginalName();
$file->move(public_path().'/images/', $name);
$blog->thumbnail = url('/images/' . $name);
}
$blog->save();
return back();
than in your view
#foreach ($blogs as $blog)
<div class="blog-item">
<div class="blog-thumb">
<img src="{{ $blog->thumbnail }}" alt=""> ->this is where i was supposed to fetch the image
</div>
<div class="blog-text text-box text-white">
<div class="top-meta">{{ Carbon\Carbon::parse($blog->created_at)->format('d-m-Y') }} / di Rakitan</div>
<h3>{{ $blog->name }}</h3>
<p>{!! \Illuminate\Support\Str::words($blog->message, 30, '...') !!}</p>
Lanjutkan Baca <img src="asset/img/icons/double-arrow.png" alt="#"/>
</div>
</div>
#endforeach
The problem with your code, I think in your store function, you did not save it correctly. Please see my code below to save link of your thumbnail into db.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Blog;
class BlogController extends Controller{
//some your function goes here
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$blog = new Blog;
$blog->name = $request->input('name');
$blog->message = $request->input('message');
$file = $request->file('your_thumbnail');
//make sure yo have image folder inside your public
$destination_path = 'image/';
$profileImage = date("Ymd").".".$file->getClientOriginalName();
$file->move($destination_path, $profileImage);
//save the link of thumbnail into myslq database
$blog->thumbnail = $destination_path . $profileImage;
$blog->save();
return redirect()->back();
}
}

Categories