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" ) }}">
Related
I'm working on a form where you have to enter all information you need and at the end, on save all information will be saved at the same times. The form have a list of images where you can add, change and delete pictures.
The way it was made is that all inputs refer to the name carousels[]. Adding the file is alright, the problem is that this way I have no way to identify in backend which file I have to delete or change.
I'm wondering if any Laravel master know a better way to handle a list of files over a form the way a need it to work. So I would be able to add new images, replace an old image by a new one and/or delete a specific image.
There are the pieces of code I'm working with.
Frontend:
#php
$carrousel = $Ids = [];
foreach ($offerImages as $index => $image) {
$carrousel[] = $image['image'];
$ids[] = $index;
}
#endphp
#for($i = 0; $i < 4; $i++)
<div class="col-sm-4 error-block">
<div class="{{ (!empty($carrousel[$i])) ? 'fileinput fileinput-exists':'fileinput fileinput-new' }}" data-provides="fileinput">
<div class="fileinput-preview thumbnail" id="banner{{$i}}" data-trigger="fileinput">
<img src="{{ !empty($carrousel[$i]) ? asset($carrousel[$i]) : (url('/') . "/images/default-thumbnail.png") }}"></div>
<div>
<span class="btn btn-secondary btn-sm btn-file">
<span class="fileinput-new ">Select image</span>
<span class="fileinput-exists">Change</span>
<input type="file" name="carrousels[]" id="carrousel{{$i}}">
</span>
Remove
</div>
</div>
</div>
#endfor
Backend
public function update(UpdateRequest $request)
{
try {
$id = $request->id;
$carrouselFolder = config('constants.DEFAULT.UPLOAD_FOLDERS.CARROUSEL');
$carrousels = [];
Log::debug($request->carrousels);
if ($request->carrousels) {
foreach ($request->carrousels as $image) {
if (!empty($image)) {
//upload image
$imageName = generateRandomString(30) . '.' . $image->getClientOriginalExtension();
if ($image->move(public_path($carrouselFolder), $imageName)) {
$image = $carrouselFolder . $imageName;
}
$carrousels[] = $image;
}
}
}
return redirect()->to(route('...'))
->with('toastSuccess', '...');
} catch (\Exception $e) {
return redirect()->back()->with('toastError', $e->getMessage());
}
}
send another parameter with old carousel, retrive it in controller then if both not empty, delete the old image . you can try this
View code
#php
$carrousel = $Ids = [];
foreach ($offerImages as $index => $image) {
$carrousel[] = $image['image'];
$ids[] = $index;
}
#endphp
#for($i = 0; $i < 4; $i++)
<div class="col-sm-4 error-block">
<div class="{{ (!empty($carrousel[$i])) ? 'fileinput fileinput-exists':'fileinput fileinput-new' }}" data-provides="fileinput">
<div class="fileinput-preview thumbnail" id="banner{{$i}}" data-trigger="fileinput">
<img src="{{ !empty($carrousel[$i]) ? asset($carrousel[$i]) : (url('/') . "/images/default-thumbnail.png") }}"></div>
<div>
<span class="btn btn-secondary btn-sm btn-file">
<span class="fileinput-new ">Select image</span>
<span class="fileinput-exists">Change</span>
<input type="text" name="oldcarrousels[{{$i}}]" value="{{ !empty($carrousel[$i]) ?$carrousel[$i] :'' }}">
<input type="file" name="carrousels[{{$i}}]" id="carrousel{{$i}}">
</span>
Remove
</div>
</div>
</div>
#endfor
Controller code
foreach ($request->carrousels as $in=>$image) {
if (!empty($image)) {
if (!empty($request->oldcarrousels[$in]) || $request->oldcarrousels[$in]!='') {
//image deleting code here
}
//upload image
$imageName = generateRandomString(30) . '.' . $image->getClientOriginalExtension();
if ($image->move(public_path($carrouselFolder), $imageName)) {
$image = $carrouselFolder . $imageName;
}
$carrousels[] = $image;
}
}
I have a product page with an image upload form built with Livewire. when i revisit the page to update information, the page will only submit if I also pass through a new image even if I update other fields. I want it to keep the current uploaded image if the image form isn't touched, allow me to update other fields without a new image upload, and upload and replace the image url when that section is updated.
I have tried all sorts of validator modifiers - nullable, sometimes, and a few if statements and i can't seem to figure it out.
Here is my upload function in my Livewire Component:
public function updateProductVariant($id)
{
$productVariant = ProductVariant::find($id);
$validated = $this->validate([
'img_url'=>'sometimes|image',
'available_end_date'=>'required',
'available_start_date'=>'required',
'notes'=>'required',
]);
$img_url = $productVariant->img_url;
if($validated['img_url'] != "")
{
$name = $productVariant->id . '.' . $validated['img_url']->extension();
$this->img_url->storeAs('public', $name);
$img_url = "/storage/$name";
}
$categories = ['Dough', 'Merch' , 'Packaging' , 'Supplies' , 'Kits' ,
'Featured' , 'Upcoming' , 'Clearance'];
foreach($categories as $category) {
if($this->$category) {
ProductCategory::updateOrCreate(['category_name'=>$category , 'product_variant_id'=>$id],[]);
} else {
ProductCategory::where('category_name' , $category)->where('product_variant_id' , $id)->delete();
}
}
ProductVariant::updateorCreate(
['id' => $id],
[
'img_url' => $img_url,
'available_end_date' => $validated['available_end_date'],
'available_start_date' => $validated['available_start_date'],
'notes' => $validated['notes'],
]);
session()->flash('message', 'Product successfully updated');
$this->resetFields();
$this->emit('gotoTop');
return redirect("corporate/cookies");
}
And my relevant blade section:
<!--/form-group-->
<div class="mb-3">
<input class="form-control form-control-lg" type="file" id="img_url" name="img_url" wire:model="img_url">
<br>
#if($img_url && !is_string($img_url))
<div style="text-align: center;"> <img src="{{$img_url->temporaryUrl()}}" alt="" class="img-fluid rounded-3" style="max-width: 50%;"></div>
#endif
<div style="text-align: center;"> <img src="{{ $img_url }}" alt="" class="img-fluid rounded-3" style="max-width: 50%;"></div>
</div>
<!--/extra-->
<br>
<div class="d-grid mb-">
<button type="submit" class="btn btn-lg btn-block btn-primary" wire:click.prevent="updateProductVariant({{$item_id}})">Update</button>
</div>
I inserted the image in my database, now I am trying to edit the images and the edited image should be deleted from my folder and a new image should be updated there. Could you please help me where I am mistaking?
Here is my Controller.php file
public function edit($slider)
{
$property=Property::all();
$slider = Slider::find($slider);
$data = ['property'=>$property, 'slider'=>$slider];
return view('admin.slider.edit', $data);
}
public function update(Request $r, $id)
{
$slider=Slider::find($id);
if( $r->hasFile('slider_thumb')){
$thums = $r->slider_thumb;
$slider_thumb = uniqid($chr).'.'.$thums->getClientOriginalExtension();
$img = Image::make($thums->getRealPath());
$img->resize(204, 107, function ($constraint) {
$constraint->aspectRatio();
});
$thumbPath = public_path().'/slider_img/'.$slider_thumb;
if (file_exists($thumbPath)) {
$this->removeImage($thumbPath);
}
$img->save($thumbPath);
$optimizerChain = OptimizerChainFactory::create();
$optimizerChain->optimize($thumbPath);
$slider_thumbimg = $slider_thumb;
}else{
$slider_thumb = NULL;
}
$slider->property_id = $r->property_id;
$slider->slider_image=$slider_imageimg;
$slider->save();
return redirect('/admin/slider');
}
}
here is my HTML file
<form class="form-horizontal" method="POST" action="{{ route('slider.update',['id'=>$slider->id]) }}" enctype="multipart/form-data">
#csrf
#method('PUT')
#if($slider->slider_image == NULL or $slider->slider_image == '')
<img src="{{asset('images/no-image-found.jpg')}}" style="width: 100px; height: 100px;">
#else
<img src="{{ asset('slider_img/'.$slider->slider_image) }}" style="width: 100px; height: 80px;">
#endif
<input type="file" name="slider_image" value="{{ $slider->slider_image }}">
<div class="form-group">
<div class="col-sm-12 text-right">
<button type="submit" class="btn btn-info">
<i class="fa fa-check"></i> Save
</button>
</div>
</div>
</form>
You did not use Laravel standards. you need to refer to laravel filesystem document to upload file. then you need to check request file exist. if request has new file; you should remove old file and upload new file. in else you should not remove old file.
follow below code:
public function store(PostRequest $request,string $slug = null)
{
$postData = $request->all();
//upload and set thumbnail of post, if exist
if($request->file("thumbnail")){
$image = new Images();
$thumbnailName = $image->uploadFile($request,"thumbnail",config("upload_image_path.post-thumbnail"));
$postData["thumbnail"] = $thumbnailName;
}
$post = $this->postService->save($postData,$slug);
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();
}
}
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.