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">
Related
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 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
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)?
I want to upload (and update) an image via Laravel.
I want an existing image name in my database to be replaced by a new one.
So I have this in my controller:
public function UpdatePic()
{
$rules = array(
'image' => 'required',
);
$random = str_random(40);
$validator = Validator::make(Input::all(), $rules);
//process the storage
if ($validator->fails())
{
Session::flash('error_message', 'Fout:' . $validator->errors());
return Redirect::to('admin/user#tab_2-2')->withErrors($validator);
}else{
//define the new random generated string for imagename
$imagename = str_random(40) . '.' . Input::file('image')->getClientOriginalName();
//store
$userimg = UserImage::find(1);
$userimg->img = $imagename;
$userimg->save();
//save the image
$destinationPath = 'public/img/user_img';
if (Input::hasFile('img'))
{
$file = Input::file('img');
$file->move('public/img/user_img', $imagename);
}
//redirect
Session::flash('success', 'Uw afbeelding is succesvol veranderd!');
return Redirect::to('admin/user#tab_2-2');
}
}
The problem is, When I Got this I'm getting this error:
Creating default object from empty value
I have a post route wich one looks like this:
Route::post('updateuserpic', 'UserController#UpdatePic');
So my view looks like this:
{{ Form::open(array('url' => 'admin/updateuserpic', 'files' => true)) }}
<div class="form-group">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
<img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=Geen+afbeelding" alt=""/>
</div>
<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;">
</div>
<div>
<span class="btn default btn-file">
<span class="fileinput-new">
Selecteer een afbeelding
</span>
<span class="fileinput-exists">
Verander
</span>
{{ Form::file('image') }}
</span>
<a href="#" class="btn red fileinput-exists" data-dismiss="fileinput">
Verwijder
</a>
</div>
</div>
<div class="clearfix margin-top-10">
<span class="label label-danger">
waarschuwing!
</span>
<span>
Dit is enkel ondersteund in de laatste versies van Firefox, Chrome, Opera, Safari and Internet Explorer 10!
</span>
</div>
</div>
<div class="margin-top-10">
{{ Form::submit('Opslaan', array('class' => 'btn green')) }}
<a href="{{ Config::get('app.url') }}/admin/user#tab_2-2" class="btn default">
Annuleer
</a>
</div>
{{ Form::close() }}
My Class only has this stuff:
<?php
class UserImage extends Eloquent{
protected $table = 'user_image';
public $timestamps = false;
}
I think the image disappears because I'm using that route, but I don't know how to fix it... It doesn't store the image in the folder and it doesn't store the random name in the database..
Thanks people!
Kindest regards,
Robin
try:
validator::make(Input::file('image'), $rules);
and change the Input from img to image:
if (Input::hasFile('image'))
{
$file = Input::file('image');
$file->move('public/img/user_img', $imagename);
}
also to edit the data in the databse, do:
UserImage::find(1)->update(['img' => $imagename]);
no need to open a object
also your route should be
Route::post('admin/updateuserpic', 'UserController#UpdatePic');
in your blade:
{{ Form::open(array('url' => 'admin/updateuserpic','method' => 'post' ,'files' => true)) }}
Update for comment
$file = array('image' => Input::file('image');
validator::make($file , $rules);
TBH, i think your code shouldn't be so complected. your Routes are fine, try changing your controller to:
<?php
public function UpdatePic(){
//first, I'll just do the file validation
$validator = Validator::make(array( 'image' => Input::file('image')),
array('image' => 'required|image'));
if($validator->fails()){
//return error code
Session::flash('error_message', 'Fout:' . $validator->errors());
return Redirect::to('admin/user#tab_2-2')->withErrors($validator);
}else{
//update the image name
$imageName = str_random(40) . '.' . Input::file('image')->getClientOrignalName();
//store
UserImage::find(1)->update(['img' => $imageName]);
//now move that image to the new location
$file = Input::file('image');
$file->move('public/img/user_img/', $imageName);
//now we have done, lets redirect back
Session::flash('success', 'Uw afbeelding is succesvol veranderd!');
return Redirect::to('admin/user#tab_2-2');
}
}
?>
The solotion I found with some help of other people wherefor thanks!
Controller:
public function UpdatePic(){
//first, I'll just do the file validation
$validator = Validator::make(array( 'image' => Input::file('image')),
array('image' => 'required|image'));
if($validator->fails()){
//return error code
Session::flash('error_message', 'Fout:' . $validator->errors());
return Redirect::to('admin/user#tab_2-2')->withErrors($validator);
}else{
//update the image name
$imageName = str_random(40) . '.' . Input::file('image')->getClientOriginalName();
//store
UserImage::where('uid', '=', Auth::user()->id)->update(['img' => $imageName]);
//now move that image to the new location
$file = Input::file('image');
$file->move('public/img/user_img/', $imageName);
//now we have done, lets redirect back
Session::flash('success', 'Uw afbeelding is succesvol veranderd!');
return Redirect::to('admin/user#tab_2-2');
}
}
The view is just an normal input.
Hope this can help other people!
Special thanks to Ashley Wrench
I used raw PHP for the job
$source = $data['Poster']; /* URL of remote image */
$dest = "posters/".$data['Year']; /* Path */
if (!file_exists($dest)) {
mkdir($dest, 0777, true); /* Create directory */
}
$dest .= "/".$data['imdbID'].".jpg"; /* Complete file name */
/* Copy the file */
copy($source, $dest);
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!