how to display images with laravel - php

I'm trying to upload images to my website but it does not show up
this is the HTML
<div class="col-md-10">
<div class="post-image">
<canvas style="display: none" id="canvas-preview" style="overflow:hidden;"></canvas>
<img id="img-preview" src="{{ url('backend/'). ($posts->preview_image?'/'. $posts->preview_image:'/post_preview/post-image.png')}}"> </div>
<div class="m-b-10">
<a id="upload-submit" class="btn btn-warning btn-block btn-sm" onclick="file.click();"><i class="fa fa-upload"></i> Upload Picture </a>
{{ Form::file('preview_image', ['class'=> 'btn btn-warning btn-block btn-sm','id'=>'file','style'=>'visibility:hidden']) }}
</div>
</div>
the controller:
public function create()
{ $this->authorize('create', Post::class);
return \View::make('posts.edit')
->with('posts', new \App\Models\Post);
}
and the model:
class Post extends Model
{
const DEFAULT_PREVIEW_IMAGE = "post_preview/post-image.png";
/**
* get preview image
* #return mixed|string
*/
public function getPreviewImage()
{
return $this->show_preview_image?$this->preview_image:static::DEFAULT_PREVIEW_IMAGE;
//return $this->preview_image;
}
}
I tried to add multiple extensions like jpg, jpeg or gif in the model but the problem persists

For laravel images should be stored in storage folder or you can create a folder inside storage folder. You also need to create symbolic link
php artisan storage:link
Here is how to upload the file to the storage folder
if ($request->hasFile('file_name')) {
$file = $request->file('file_name');
$fileName = str_replace(' ', '-', $file->getClientOriginalName());
$uploadPath = storage_path('app/public/folder_name');
$path = $request->file('file_name')->move($uploadPath, $fileName);
$uploadPathFile = $fileName;
}
Then you save the path to your DB.
For showing the image in the blade
<img src="/storage/folder_name/{{$data->image}}" alt="No image available" class="img-thumbnail">
Here $data->image is only the path

is your image stored in a public directory - try accessing the URL in your browser to see if the response is the expected image.
If not please provide more details how are you trying to retrieve the image (via binary response or stored as a public asset)?

Related

intervation image wont store image in public path after i uploaded my laravel project on host

i have a project that it has some posts on it
i have made admin panel to create new posts
since i uploaded my project on cpanel host i can create a post but image wont shown in my post but before that on my localhost i can craete a post and store image in my path
i checked my public path in my host and saw that there isn,t any new image related to my post that i have created with my admin panel on my host just my image name has saved in my database
this is my blog blade file
<section class="w-80 mx-auto my-5">
<div class="container">
<div class="row">
#foreach($posts as $post)
<div class="col-md-4 translate-box relative mb-4">
<div class="blog-box-height">
<img src="{{asset('image/'.$post->header_image)}}" alt="{{$post->title}}" class="img-fluid">
<div class="py-3 px-4">
<a class="text-xmedium fw-bold text-decoration-none text-black" href="{{route('blog.single',['title'=>$post->title])}}">
{{str_replace('_',' ',$post->title)}}
</a>
<p class="text-muted-1 mt-2 text-small">
{!! strip_tags(mb_substr($post->content,0,270,'utf-8')) !!} ...
</p>
<div class="box-time absolute">
<p class="text-muted-1"><i class="far fa-clock"></i> {{$post->time}} دقیقه</p>
</div>
</div>
</div>
</div>
#endforeach
</div>
</div>
</section>
this is my postcontroller codes
public function storeImage(Request $request)
{
$image_name = null;
if ($request->file('image')) {
$image = $request->file('image')->getClientOriginalName();
$image_name = time() . $image;
$folder = public_path('/image');
$path = $folder . '/' . $image_name;
if (is_dir($folder)) {
$img = Image::make($request->file('image'))->resize(500, 438);
$img->save($path);
} else {
File::makeDirectory($folder, 0755, true);
$img = Image::make($request->file('image'))->resize(500, 438);
$img->save($path);
}
}
return $image_name;
}
this code works great in my localhost server but when i uploaded it on host i think image intervation wont work
You have to set the symlink to connect the stroge folder with the public folder.
Try running php artisan storage:link on the webserver.
Also in some hostings this command is banned. In that case you have to create the symlink manually using forexample midnight commander.
Try with 777 permission for make directory.
File::makeDirectory($folder, 0777, true);

How to print an image with DomPDF in laravel?

I am making a pdf, for which I use the library: barryvdh/laravel-dompdf, in the pdf I try to print an image, with which when I open the recently downloaded file, all the data is printed except the image, I clarify this image if it is displayed correctly in my show.blade view, I cannot find a solution for this problem.
Below I detail how I am proceeding:
Controller: (fragment of store method and exportPdf method)
public function store(SaveDocumentRequest $request)
{
if ($request->hasFile('photo')) {
$file = $request->file('photo');
$name = time().$file->getClientOriginalName();
$file->move(public_path().'/images/', $name);
}else{
$name = null;
}
$document->photo = $name;
public function exportPdf()
{
$movie = Movies::with('document.creator', 'actors', 'generate_movie', 'document.adequacy', 'document.lenguage')->first();
$pdf = PDF::loadView('admin.movies.show', compact('movie'));
return $pdf->download('cine.pdf');
}
My show.blade file:
<div class="col-md-6">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Imagen de Portada </h3>
</div>
<div class="box-body box-profile">
<img class="img-responsive" src="{{ asset('/images/'.$movie->document->photo) }}" alt="{{ $movie->document->title }}" >
</div>
</div>
</div>
This way I am accessing the image that if it is displayed correctly in my show.blade file, but it is not displayed in the downloaded pdf.
I clarify I do not receive any type of error and the image is stored in the public folder of the project.
Could you guide me to find the solution?
Its simple just use this I have used same package and added image on pdf like this.
<img src="{{asset('foldername/path_to_image')}}">

Trouble getting the image out from public folder with a one-to-one relationship

I am having some trouble getting the image from the public folder where in the database, I have UserImage table and personal_info table and they are connected together in a one to one relationship. I have tried using this but it just return me blank results.
Here are the codes:
HomeController:
public function getInfo($id) {
$data = personal_info::where('id', $id)->get();
$data3 = UserImage::where('user_id', $id)->get();
return view('test',compact('data', 'data3'));
test.blade.php (where I show the image)
#foreach ($data as $object)
<b>Name: </b>{{ $object->Name }}<br><br>
#foreach ($data3 as $currentUser)
<img src="{{ asset('public/images/' . $currentUser->name ) }}">
#endforeach
#if ($data3->count())
#foreach ($data3 as $currentUser)
<a href="{!! route('user.upload.image', ['id' => $currentUser->user_id]) !!}">
<button class="btn btn-primary">
<i class ="fa fa-plus"></i>Upload Images
</button>
</a>
#endforeach
#else
<a href="{!! route('user.upload.image', ['id' => $object->id]) !!}">
<button class="btn btn-primary">
<i class ="fa fa-plus"></i>Upload Images
</button>
#endif
#endforeach
Create1Controller:
public function store1(Request $request)
{
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = $image->getClientOriginalName();
$size = $image->getClientSize();
$id = $request->user_id;
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$userImage = new UserImage;
$personal_info = new personal_info;
$userImage->name = $name;
$userImage->size = $size;
$user = personal_info::find($id);
$user->UserImages()->save($userImage);
}
return redirect('/home');
}
Since you are not saving your assets into storage and saving into your public directory you could use the url() method instead. If you need to stick with asset() you need to create a symlink from the storage directory to the public directory which is explained here, and use the storage directory to save your assets.
As I see, there is no relation between saved image name and the $currentUser->name
Can you show your code you use to save the image? There you have to save the image with current user name.
The error here: $image->move($destinationPath, $name);

How to display a new image right away after successfully uploaded?

I implemented a logo upload system. It would take effect right away. It require me to refresh the page to see the effect. I'm wondering how do I stop that.
IMG
<img id="userLogo" src="/images/account/operator/logo.png" alt="" class="thumbnail img-responsive">
Form
{!! Form::open(array('url' => '/profile/logo/update', 'class' => 'form-horizontal', 'role' =>'form','id' => 'editLogo','files'=>true)) !!}
<input name="logo_path" type="file"> <br><br>
<button class="btn btn-success btn-sm mr5" type="file"><i class="fa fa-user"></i> Update Logo</button>
{{ csrf_field() }}
{!! Form::close();!!}
Controller
public function updateLogo(){
$inputs = Input::all();
$logo_path = array('logo_path' => Input::file('logo_path'));
$rule = ['logo_path' => 'max:100|mimes:jpeg,bmp,png'];
$id = Auth::user()->account_id;
$type = Auth::user()->account_type;
$validator = Validator::make($logo_path, $rule );
if ( $validator->fails()) {
return Redirect::to('/profile/')->withErrors($validator)->withInput();
} else {
$old_logo_path = public_path().'/images/account/operator/logo.png';
$delete = File::delete($old_logo_path);
if (Input::hasFile('logo_path'))
{
$file = Input::file('logo_path');
$destinationPath = public_path().'/images/account/operator/';
$uploadSuccess = $file->move($destinationPath, 'logo.png');
}
return Redirect::to('/profile/')
->with('success','Your company logo was updated succesfully!');
}
}
Result
My file got saved to the place I want them to be.
But when the old logo is still showing on the page
unless, I refresh the page, then, I'll see my new one.
Any hints / suggestions on this will be much appreciated !
This is because the image is cached in browser, and since you are updating an image with same name browser shows the already cached image. hence the better and effective solution is to have a unique file name every time you upload an image or you can append a querystring to the image path every time you serve an image.
<img id="userLogo" src="/images/account/operator/logo.png?q=<?php echo microtime(); ?>" alt="" class="thumbnail img-responsive">

How do I delete and update a photo in Laravel 4?

In my application, a user can upload an image for their profile photo. How do I update a users photo and the delete the previously uploaded photo? This is what I have so far in the upload controller:
Photos Model
class Photos extends Eloquent {
protected $table = 'photos';
protected $fillable = array('user_id', 'location');
public function user (){
return $this->belongsTo('User');
}
}
user model
public function photos()
{
return $this->hasOne('photos');
}
Upload Controller
class UploadController extends \BaseController {
public function postUpload (){
$id = Auth::user()->id;
$input = Input::all();
$rules = array(
'photo' => 'required|image|max:500'
);
$validator = Validator::make($input, $rules);
if($validator->fails()){
return Redirect::to('user/profile/'.$id.'/edit')->withErrors($validator);
}
$extension = Input::file('photo')->getClientOriginalExtension();
$directory = public_path('/var/chroot/home/content/59/11581559/html/beta') . '/uploads/'.sha1($id);
$filename = sha1($id.time()).".{$extension}";
$upload_success = Input::file('photo')->move($directory, $filename);
Image::make(Input::file('photo')->getRealPath())->resize(300, 200)->save('foo.jpg');
if($upload_success){
$photo = new Photos(array(
'location' => URL::to('/uploads/'.sha1($id).'/'.$filename)
));
$photo->user_id = $id;
$photo->save();
Session::flash('success_photo', 'You have Successfully uploaded your profile photo!');
return Redirect::to('user/profile/'.$id.'/edit');
}
else{
Session::flash('status_error', 'An Error has occurred while uploading your photo. Please try again!');
}
return Redirect::to('user/profile/'.$id.'/edit');
}
}
View
<div class="col-lg-3">
<div class="panel panel-default">
<div class="panel-heading">
#if(Session::has('status_error'))
<div class="alert alert-error">
<a class="close" data-dismiss="alert" href="#" aria-hidden="true">×</a>
{{ implode('', $errors->all('<li class="error"><b>:status_error</b></li>')) }}
</div>
#endif
<span class="glyphicon glyphicon-exclamation-sign"></span> Upload a Photo
</div>
<div class="panel-body text-center">
#if($user->photos)
<img width="190" height="119" class="img-responsive img-thumbnail" src="{{$user->photos->location }}" alt="">
#endif
<div class="clearfix"></div>
<div class="btn-group mtop-20">
<button type="button" class="btn btn-primary" onclick="$('#upload_modal').modal({backdrop:'static'});">
<span class="glyphicon glyphicon-upload"></span>
</button>
</div>
</div>
<?php echo View::make('modals.photo-upload') ?>
</div><!-- end panel-default -->
</div><!-- col 3-->
Let's talk about what you're doing and work from there.
Uploading a Photo
- In your controller, you're uploading a photo.
- If the upload succeeds, you're storing the location of the photo on your server as well as the ID of the user to whom the photo belongs.
Updating a Photo
- In your controller, you're uploading a photo.
- If the upload succeeds, you're going to:
Get the location of the current file in the database.
$this->photo->where('user_id' , '=' , $the_user_id_in_question)
->get(array('location'));
Delete the file at that location using the delete() function in the FileSystem class (found here: https://github.com/laravel/framework/blob/master/src/Illuminate/Filesystem/Filesystem.php)
Update the user's photo location with the new one:
$this->photo->where('user_id' , '=' , $the_user_id_in_question)
->update('location' => $the_new_upload_location);
I hope that's what you're looking for. Cheers!

Categories