why my old image can't be deleted when i uploaded new image?
this is my controller where i use to store data and image.
my file image name is stored combination from nama_post_adps and from $imageName where that is query for getClientOriginalName();
public function update(Request $request, Adopsi $adopsi, $id)
{
$getParentJenisHewan = JenisHewan::where("id", $request->jenis_hewan_id)->value("nama_jenis_hewan");
$getParentRasHewan = RasHewan::where("id", $request->ras_hewan_id)->value("nama_ras_hewan");
$imageSize = $request->file('image_post_adps')->getSize();
$imageName = $request->file('image_post_adps')->getClientOriginalName();
$pathstorage = $request->file('image_post_adps')->storeAs('public/post/adopsi',$request->nama_post_adopsi.'-'.$imageName);
$adopsiAttr = $this->validasiRequest();
$adopsiAttr = $request->all();
$adopsiAttr['nama_jenis_hewan'] = $getParentJenisHewan;
$adopsiAttr['nama_ras_hewan'] = $getParentRasHewan;
$adopsiAttr['image_post_adps'] = $imageName;
$adopsiAttr['path-storage'] = $pathstorage;
$adopsiAttr['size'] = $imageSize;
$adopsi = Adopsi::find($id)->update($adopsiAttr);
$delete = Adopsi::find($id);
unlink('app/public/post/adopsi/'.$delete->nama_post_adopsi.'-'.$delete->image_post_adps);
// if ($request->file('image_post_adps')) {
// Storage::disk('public')->delete('/post/adopsi/'.$request->nama_post_adopsi.'-'.$request->image_post_adps);
// }
if($adopsi) {
return redirect()->route('adopsi.index')->with('success','Data '.$request->nama_post_adopsi .' telah mendapatkan update terbaru.');
} else {
return redirect()->route('adopsi.index')->with('error','Data gagal'.$request->nama_post_adopsi .'diupdate');
}
}
method above literally same with my store method .
i've try unlink() but it can't work and show error : unlink('post/adopsi/..') no such file or directory , but field can't be updated. then i decided use Storage::disk('public')->delete , field got update, the image change with new but old still same.
You are doing wrong.
First fetch existing data and check if request has file then delete old one then update it
$delete = Adopsi::find($id);
if ($request->file('image_post_adps')) {
Storage::disk('public')->delete('/post/adopsi/'.$delete->nama_post_adopsi.'-'.$delete->image_post_adps);
}
$adopsi = Adopsi::find($id)->update($adopsiAttr);
Related
i am trying to do an update using dynamic for "education history" but there is an image also, i use eloquent to update too, for some reason the data is saved in the database but the image just tmp and cannot find in the folder.
//count array data inputed
for($incs=0; $incs < count($data_detail_user['institution_names']); $incs++) {
// update education
foreach( $data_detail_user['institution_names'] as $key => $file ){
// get old photo thumbnail
$get_photo = Educations::where('id', $key)->first();
// store photo
$path = $file->store(
'assets/education/thumbnail', 'public'
);
$education_user = Educations::find($incs);
$education_user->detail_user_id = $detail_user['id'];
$education_user->name = $data_detail_user['institution_names'][$incs];
$education_user->course = $data_detail_user['education_courses'][$incs];
$education_user->start = $data_detail_user['education_starts'][$incs];
$education_user->graduate = $data_detail_user['education_graduates'][$incs];
$education_user->address = $data_detail_user['education_addresses'][$incs];
$education_user->regencies = $data_detail_user['education_regencies'][$incs];
$education_user->provinces = $data_detail_user['education_provinces'][$incs];
$education_user->country = $data_detail_user['education_countries'][$incs];
$education_user->zip_code = $data_detail_user['education_zips'][$incs];
$education_user->certificate = $data_detail_user['education_certificates'][$incs][$path];
$education_user->save();
$data_detail_user = 'storage/' .$get_photo['certificate'];
if (File::exists($data_detail_user)) {
File::delete($data_detail_user);
} else {
File::delete('storage/app/public/' .$get_photo['certificate']);
}
}
}
[the error show Call to a member function store() on string]
this is the screenshoot of the error
[1]: https://i.stack.imgur.com/l96sm.png
$path = $request->file('path')->store('public/post');
I assume you have a directory where the image is suppose to be stored that's why i created the post directory after public.
It's my update function and it's not showing image when I echo $fileName. It's not working like it was I want to make it with the condition if there is any image then update that image otherwise leave that I tried many times but it's not working.
public function update(Request $request, Header $header)
{
if($request->hasFile('headerimg')){
$fileName = $request->file('headerimg')->getClientOriginalName();
$request->file('headerimg')->move('uploads/header',$fileName);
}
$header->title = $request->title;
$header->discription = $request->discription;
$header->keywords = $request->keywords;
$header->headerimg = $fileName;
$header->h2 = $request->h2;
$header->breadcumb = $request->breadcumb;
$header->category = $request->category;
$header->save();
return redirect()->route('dashboard.headers.index')->with('success', 'Packages Edited Successfully');
}
I guess that your problem is in your view.
Maybe you forget to use enctype="multipart/form-data" or your input name does not match with mapped controller variable.
For find the exact problem use dd($request) and dd($request->file('headerimg')) and see can you get request correct or not.
I use this code edit image and if image was not selected the old image will remain same without any error.
public function update(Request $request, Header $header)
{
$file = $request->headerimg;
$id = $request->id;
if($file == ''){
$arr['header'] = Header::select()->where($id);
$fileName = $header['headerimg'];
}
else{
$fileName = $request->file('headerimg')->getClientOriginalName();
$request->file('headerimg')->move('uploads/header',$fileName);
}
$header->title = $request->title;
$header->discription = $request->discription;
$header->keywords = $request->keywords;
$header->headerimg = $fileName;
$header->h2 = $request->h2;
$header->breadcumb = $request->breadcumb;
$header->category = $request->category;
$header->save();
return redirect()->route('dashboard.headers.index')->with('success', 'Page Edited Successfully');
}
im trying to upload multiple images with laravel 5.4, actually the process to upload images is done, the question is how to store them in database?
for example when gonna create a slide show of something that has several images that is uploaded, how to group them so the slide show knows those images are in one group?
can you guys help me?
Make sure you go to config/filesystems and turn 'FILESYSTEM_DRIVER' to 'public'
Model to store image paths:
class UserDocuments extends Model
{
//
protected $table = 'user_documents';
public function store($user_id, $document_link, $file_name)
{
$this->user_id = $user_id;
$this->document_link = $document_link;
$this->file_name = $file_name;
$this->save();
}
}
Code in controller to store files ('document' is file input field name)
if ($request->hasFile('document')) {
$link = $request->file('document')->store('documents');
}
$userDocuments->store(request('user_id'), url($link), $link);
To show if the images are in a group, you would have to create a database column called 'group_id' and sort them accordingly.
We have to store images into one records/row by separting commas.
class DocumentController extends Controller
{
public function store(Request $request)
{
$pid = $request->input('pid');
$input = $request->file('files');
$picture = array();
if($request->hasFile('files')) :
foreach ($images as $item):
$extension = $item->getClientOriginalName(); //image extension
$name = time() . '.' .$extension; //image name
$item->move('uploads/documents/', $name); //move to destination
$arr[] = $name; //store image into array
endforeach;
$picture = implode(",", $arr); //Image separated by comma
else:
$picture = '';
endif;
DB::table('document')->insert(array('pid' => $pid,'image' => $picture));
Session::flash('message', 'Multiple Images are uploaded successfully');
return redirect('/multiple-image');
}
}
I need to display the stored images in my view.I've used the below code to store image in db,
$file = Input::file('pic');
$img = Image::make($file);
Response::make($img->encode('jpeg'));
$picture = new Car;
$picture->cartype = Input::get('cartype');
$picture->price = Input::get('price');
$FileName = Input::file('pic')->getClientOriginalName();
$FilePath = public_path('') .'/images/'. $FileName;
$picture->name = $FilePath;
$picture->save();
In my controller( to retrieve image)
public function index()
{
$cars = DB::table('car_category')->get();
return view('category.category',['cars'=>$cars]);
}
How should I retrieve and display the images in view?
If you are storing the image name in the database and uploading it in a directory then you can easily display it by simply fetching the name from database, returning the name to view and append the name to a hard-coded directory address like this -
<img src="/images/{{ $imageVariableName }}">
Let me know if this works.
i build function to upload zip files but when user upload file two times it didnt delete the first uploaded file but added increment number to the file name (( file.zip,file1.zip,file2.zip,,,etc )
so i want to tell the function when the user uploaded the same file name delete the first file and upload this second file or replace it ... anyone help me how to do that...
/**
* change book source file
*
* #param integer $book_id
*/
public function upload_book_zip($book_id) {
$vars = array();
$vars['upload_path'] = PUBPATH . 'global/modules/bookstore/files/books_source_file/';
$vars['allowed_types'] = 'zip';
$vars['max_size'] = '30720';
$vars['book_id'] = $book_id;
$book = $this->d_book->find_by_id($book_id);
if (isset($_POST['submit'])) {
$file_name = $this->upload($vars);
if ($file_name === NULL) { // error happens while uploading file
$vars['upload_errors'] = $this->upload->display_errors("<p class='notification n-error'>", "</p>");
} else {
$this->d_book->update_one_field($book_id, 'bo_path_zip', $file_name);
$this->session->set_flashdata('success_msg', lang('file_uploaded'));
redirect('bookstore/admin_d_book/');
}
} else {
$vars['upload_errors'] = NULL;
}
if ($book->bo_path_zip) { // load cover image
$vars['file_path'] = base_url() . 'global/modules/bookstore/files/books_source_file/' . $book->bo_path_zip;
} else {
$vars['file_path'] = NULL;
}
$vars['controller_name'] = 'admin_d_book';
$this->view('bookstore/admin/change_zip_file', $vars);
}
/**
*
* #param array $config the configuration array
* #return string
*
*/
private function upload($config) {
$this->load->library('upload', $config);
if (!$this->upload->do_upload("file")) {
return $uploadData['file_name'] = NULL;
} else {
$uploadData = $this->upload->data();
log_message('debug', 'file has been uploaded ok - file name is ' . $uploadData['file_name']);
return $uploadData['file_name'];
}
}
you can do that by adding
$vars['overwrite'] = TRUE;
better check File upload library
Set overwrite to true in the config array you pass
$vars = array();
$vars['upload_path'] = 'filepath here';
$vars['allowed_types'] = 'zip';
$vars['max_size'] = '30720';
$vars['book_id'] = $book_id;
// add this line
$vars['overwrite'] = true;
// the old file will now get overwritten
$file_name = $this->upload($vars)
A better method is to check the md5 or sha1 checksum of the file.
If two users uploads two different files with the same name to the server, the file on server will be overwritten and it is impossible to distingush the file by just name.
Also, it can be done easily in PHP.