I am currently trying to delete an image when a user updates his/her post before publishing.
Everything works fine, the image is changed in the database and post page, but I want to delete the previous image.
Here is my controller
public function updatePost(Request $request){
$data = $request->all();
$postid = $request['id'];
$isExist = Post::where('id', $postid)->first();
if($isExist){
if ($request->hasFile('image')) {
$file = $request->File('image');
//Get filename with extension
$fileNameToStoreWithExt = $file[0]->getClientOriginalName();
//Get just filename
$filename = pathinfo($fileNameToStoreWithExt, PATHINFO_FILENAME);
//Get just ext
$extension = $file[0]->getClientOriginalExtension();
//File to store
$fileNameToStore = $filename . '_' . time() . '.' . $extension;
//Upload Image
$path = $file[0]->storeAs('image', $fileNameToStore);
$file[0]->move('storage/image', $fileNameToStore);
File::delete(public_path('storage/image'.$isExist['image']));
Post::where('id', $postid)->update([
'title' => $data['title'],
'category' => $data['category'],
'content' => $data['content'],
'image' => $path
]);
return response()->json([
'status'=>'200',
'response'=> 'successfully updated'
]);
}else{
Post::where('id', $postid)->update([
'title' => $data['title'],
'category' => $data['category'],
'content' => $data['content']
]);
return response()->json([
'status'=>'200',
'response'=> 'successfully updated'
]);
}
}else{
return response()->json([
'error'=> 'post does not exist'
]);
}
}
I used:
File::delete(public_path('storage/image'.$isExist['image']));
but it didn't do the job
my delete function
public function deletePost($id){
$post = Post::where('id',$id)->first();
// dd($post);
if(!$post){
return response()->json([
'status' => '500',
'error' => 'post not found'
]);
}
Storage::disk('public')->delete('/storage/image'. $post['image']);
Post::where('id', $id)->delete();
return response()->json([
'status'=> '200',
'response'=> 'Post successfully deleted'
]);
}
my storage path snapshot
use Illuminate\Support\Facades\Storage;
Storage::delete('file.jpg'); // delete file from default disk
Storage::delete(['file.jpg', 'file2.jpg']); // delete multiple files
Storage::disk('your_disk')->delete('file.jpg'); // delete file from specific disk e.g; s3, local etc
Please refer link https://laravel.com/docs/6.x/filesystem
If you look at laravel file-system documentation you will see there are multiple Disk laravel support. you can used Storage Facades to delete a file from Storage like this
use Illuminate\Support\Facades\Storage;
Storage::disk('local')->delete('folder_path/file_name.jpg');
path should be like this for public directory.
Storage::disk('local')->delete('public/image/'.$filename);
its easy to do an if statement and delete old image on updating! this code is an example edit it to your requirements.
if ($request->hasFile('file')) {
Storage::delete($myImage->file); // If $file is path to old image
$myImage->file= $request->file('file')->store('name-of-folder');
}
Another :
File::delete(public_path('images/'. $oldFilename));
see here : https://laracasts.com/discuss/channels/laravel/delete-old-image-from-public-folder-after-updating
You can use normal PHP delete file keyword #unlink
if (file_exists($image)) {
#unlink($image);
}
You can use File to delete file from specific path
$file= "image path here";
\File::delete($file);
Delete uploaded file from public dir
OR
You can use unlink for the same
$image_path = "image path here";
if (file_exists($image_path)) {
#unlink($image_path);
}
PHP -> unlink
Related
i want to update forums table that contains
fr_user_id
fr_author
fr_title
fr_body
fr_filename
code in my controller :
$request->validate([
'fr_user_id' => 'required',
'fr_author' => 'required',
'fr_title' => 'required',
'fr_body' => 'required'
]);
$input = $request->all();
if ($image = $request->file('fr_filename')){
$destinationPath = public_path('/images');
$imgName = time() . '.' . $image->getClientOriginalExtension();
$image->move($destinationPath, $imgName);
$input['fr_filename'] = "$imgName";
} else {
unset($input['fr_filename']);
}
$forum = Forum::find($id);
$forum->update($input);
return redirect('/user/myforum')->with('success','Update Successfull');
my Routes
Route::match(['put','patch'],'/forum/update/{id}',[ForumController::class,'update'])->name('forum/update');
this code is working but the 'fr_filename' data is become null in my db, what should i do?
Had you checked, file is coming in request?
The post created is to save the image and description to the DB but only the description gets saved.The request is being done via formData()..So currently trying via postman
$post = new Post;
$post->user_id = Auth::user()->id;
$post->desc = $request->desc;
//check if post has photo
If($request->hasFile('image')){
$imageName = time().'.'.$request->image->extension();
$request->image->move('storage/posts', $imageName);
$post->photo = $imageName ;
}
//mistake
$post->save();
$post->user;
return response()->json([
'success' => true,
'message' => 'posted',
'post' => $post
]);
1_check directory has permission 777
2_$request->file('image')->move("directory", "new file name");
if($request->file('image') !=null){
$request->file('image')->move("directory", "new file name")
}
I am facing this error while uploading an image with a title and description text to DB in PHP Laravel. I am using the same code for other webpage there it is working properly but the same code is not working here.
Below is a function code inside my controller, where I am passing tile, description, img and input names from a form.
public function submitFanfic(Request $request){
$user_id = session('userid');
$name = $_FILES['img']['name'];
$tem_name = $_FILES['img']['tmp_name'];
$dir = 'public/uploads/fanfic/';
$dir1 = $dir.$name;
move_uploaded_file($tem_name, $dir1);
$data = array(
'fanfic_title' => $request['title'],
'fanfic_desc' => $request['description'],
'img' => $name,
'user_id' => $user_id
);
DB::table('fanfic')->insert($data);
Session::flash('message', 'Fanfic Submitted Successfully');
return redirect('/author/write_fanfic');
}
I tried again and again and this code (specifically for image insertion into DB) worked!!
public function submitFanfic(Request $request){
$user_id = session('userid');
$imageName = $request->file('img');
if($imageName!==null){
// get the extension
$extension = $imageName->getClientOriginalExtension();
// create a new file name
$new_name = date( 'Y-m-d' ) . '-' . str_random( 10 ) . '.' . $extension;
// move file to public/images/new and use $new_name
$imageName->move( public_path('uploads/fanfic'), $new_name);
}
$fanfic_data = array(
'fanfic_title' => $request['title'],
'fanfic_desc' => $request['description'],
'img' => $new_name,
'user_id' => $user_id
);
DB::Table('fanfic')->insert($fanfic_data);
Session::flash('message', 'Fanfic Submitted Successfully');
I'm pretty new to Laravel, thus I'm trying to learn some of the basics. I have managed to create a CRUD with file upload. What I did was I created a resource controller. My store method:
public function store(Request $request) {
$this->validate($request, [
'name' => 'required',
'avatar' => 'required|image|mimes:jpeg,png,jpg,gif,svg',
'boat_type' => 'required',
'rooms' => 'required',
'price_per_hour' => 'required',
'price' => 'required',
]);
$boat = new Boat($request->input()) ;
if($file = $request->hasFile('avatar')) {
$file = $request->file('avatar') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/img/boats/avatars/' ;
$file->move($destinationPath,$fileName);
$boat->avatar = $fileName ;
}
$boat->save() ;
return redirect()->route('management.index')
->with('success','New Boat Successfully Added!');
}
This method works perfectly fine, with this I am able to upload and store the details to my database and am able to manipulate it in my view.
But when I try to use the UPDATE method I have the exact code.. yet when I try to update my post everything can be updated except my avatar variable. it updates it but it stores it in a strange format. Here is my UPDATE method
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'boat_type' => 'required',
'rooms' => 'required',
'price_per_hour' => 'required',
'price' => 'required',
]);
$boat = Boat::find($id);
if($file = $request->hasFile('avatar')) {
$file = $request->file('avatar') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/img/boats/avatars/' ;
$file->move($destinationPath,$fileName);
$boat->avatar = $fileName ;
}
$boat->save() ;
$boat_update = $request->all();
$boat->update($boat_update);
$request->session()->flash('alert-success', 'Boat Successfully Updated!');
return redirect('/management');
}
When I edit the avatar variable it stores it in /img/boats/avatars/C:\xampp\tmp\phpFA50.tmp
I'm not really sure what is wrong. Any help will be greatly appreciated.
$boat->save() ; you don't need to save before update -> remove it
$boat_update = $request->all(); -> Your filename is NOT in there
$boat->update($boat_update); Are all the fields $fillable? If yes you need to add the new filename to that array
Found the solution, it was pretty much a logic error as I was simply saving the file name then overwriting it with the $request->all()
The correct solution would be this:
$boat = Boat::find($id);
$boat->fill($request->except('avatar'));
if($file = $request->hasFile('avatar')) {
$file = $request->file('avatar') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/img/boats/avatars/' ;
$file->move($destinationPath,$fileName);
$boat->avatar = $fileName ;
}
$boat->save();
$request->session()->flash('alert-success', 'Boat Successfully Updated!');
return redirect('/management');`
I am trying to validate uploaded files using laravel validation but am having issues.
Here is my code:
$this->validate($request, [
'image' =>'mimetypes:image/jpeg,image/png,image/gif',
]);
$avatar = $request->file('image');
$fileName = time(). '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300,300)->save( public_path('uploads/avatar/' . $fileName));
$user = Auth::user();
$user->avatar = $fileName;
$user->save();
The issue is when I use a bmp file, I get this error:
Gd error
I am using the Intervention image package. I would rather not switch to the imagick driver.
Any ideas?
Looking at the Intervention package code, you can see two implementations to the processBmp function:
Intervention/Image/Gd/Encoder.php:
protected function processBmp()
{
throw new \Intervention\Image\Exception\NotSupportedException(
"BMP format is not supported by Gd Driver."
);
}
Intervention/Image/Imagick/Encoder.php:
protected function processBmp()
{
$format = 'bmp';
$compression = \Imagick::COMPRESSION_UNDEFINED;
$imagick = $this->image->getCore();
$imagick->setFormat($format);
$imagick->setImageFormat($format);
$imagick->setCompression($compression);
$imagick->setImageCompression($compression);
return $imagick->getImagesBlob();
}
So I think it's safe to say that you can't do it with the GD driver, only with imagick.
Simply use "intervention/image": "~2" or change your driver to Imagick. It is a known issue that GD does not natively support BMP. You can check the issue page on github for details.
Why you don`t use Laravel custom rule for image image?
$this->validate($request, [
'image' =>'image',
]);
hope this solution will fix your error, please try with below logic
public function postUpload(Request $request)
{
$input = $request->all();
$rules = array(
'uploadFile' => 'image|max:8000'
);
$validation = Validator::make($input, $rules);
if ($validation->fails())
{
return array(
'validation_failed' => true,
'errors' => $validation->errors()->toArray()
);
}
$file = $request->uploadFile;
$destinationPath = 'uploads/img';
// Get real extension according to mime type
$ext = $file->extension();
// Hash processed file name, including the real extension
$hashname = date('H.i.s').'-'.md5($request->_token).'.'.$ext;
$upload_success = $request->uploadFile->storeAs($destinationPath, $hashname);
Image::configure(array('driver' => 'imagick'));
$img = Image::make(storage_path() . '/app/uploads/img/' . $hashname);
$img->resize(230, null, function ($constraint) {
$constraint->aspectRatio();
});
$img->save(storage_path() . '/app/uploads/lowres/' .$hashname ,80);
$user_image = new User_images();
$user_image->id_user = Auth::user()->id;
$user_image->handler = $hashname;
$user_image->save();
return array('status' => 'success','message'=> 'Image has been uploaded successfully','file_path'=>'/uploads/'.$hashname);