unlink image only if exists in laravel - laravel

While updating the user image unlink image from public folder if exists otherwise do update the user with image. Currently I have no image for user. And while updating user from profile section I am getting this error unlink('images/users') is a directory. I want if image exists for user then unlink the image and upload the new one otherwise just upload the new image.
My controller:
public function changeUserImage(Request $request)
{
$this->validate($request, [
'image' => 'required|mimes:jpeg,jpg,png|max:10000',
]);
$image = $request->file('image');
if (isset($image)) {
$imageName = time() . '.' . $request->image->getClientOriginalExtension();
if (!file_exists('images/users')) {
mkdir('images/users', 0777, true);
}
if (file_exists('images/users')){
unlink('images/users/' . \auth()->user()->image);
$image->move('images/users', $imageName);
User::find(\auth()->user()->id)->update(['image'=>$imageName]);
}else if (!file_exists('images/users')){
$image->move('images/users', $imageName);
User::find(\auth()->user()->id)->update(['image'=>$imageName]);
}
}
return redirect()->back();
}

Try this. I haven't test it yet. Let me know if you have any questions.
Make sure to Import File: use File;
UPDATED
public function changeUserImage(Request $request)
{
$this->validate($request, [
'image' => 'required|mimes:jpeg,jpg,png|max:10000',
]);
// Let get the current image
$user = Auth::user();
$currentImage = $user->image;
// Let compare the current Image with the new Image if are not the same
$image = $request->file('image');
// The Image is required which means it will be set, so we don't need to che isset($image)
if ($image != $currentImage) {
// To make our code cleaner let define a directory for DRY code
$filePath = public_path('images/users/');
$imageName = time() . '.' . $request->image->getClientOriginalExtension();
if (!File::isDirectory($filePath)){
File::makeDirectory($filePath, 0777, true, true);
}
$image->move($filePath, $imageName);
// After the Image has been updated then we can delete the old Image if exists
if (file_exists($filePath.$currentImage)){
#unlink($filePath.$currentImage);
}
} else {
$imageName = $currentImage;
}
// SAVE CHANGES TO THE DATA BASE
$user->image = $imageName;
$user->save();
return redirect()->back();
}

To store the image: $request->image->storeAs('images/users/', $file_name);
To delete an image: Storage::delete('images/users/'. $file_name);

Related

some images gets duplicated after the uploading - laravel

i am using a function that uploads multiple images and it was working perfectly locally but after deployment i am having this duplication issue .
i upload img1 and img2 and img3 but in the database i find only one of them like img1.jpg and the same thing in the folder .
public function _articleGalleryUpload(Request $request)
{
$article = Blog::find($request->id);
$img = $request->Otitle;
//dd($img);
$request->validate([
'images'=> 'required',
'images.*'=> 'image|mimes:jpg,png,jpeg|max:4000'
]);
if(!File::isDirectory('assets/images/blogs/gallery/'.$img)){
File::makeDirectory('assets/images/blogs/gallery/'.$img);
}
$images = $request->file('images');
if($request->hasFile('images'))
{
foreach( $images as $image )
{
//$extension = $file->getClientOriginalExtension();
$ImageName = '_' . time() .'.' . $image->getClientOriginalExtension();
$path = $image->move(('assets/images/blogs/gallery/'.$img), $ImageName);
$imageP = Image::make($path)->resize(600, null, function ($constraint) {
$constraint->aspectRatio();
});
$galerie = new blogsGallery;
$galerie->Img = $ImageName;
$galerie->idart = $request->id;
$galerie->alt = $img;
$imageP->save();
$galerie->save();
}
return back()->with('success', 'les images ont été téléchargées');
}
}
i tried using array to store the names of the images but it didn't work, it uploads one image instead of multiple .
Your code has one issue.
$path = $image->move(('assets/images/blogs/gallery/'.$img), $ImageName);
this code is error.
$img is one name for several images.

Updating an image in laravel does not save to DB, only saves when adding new record

I have the form of a service where a name, description, and photo is required. When adding a new service the form works fine, everything is saved in the database.
Problem is when I want to change the photo and upload a new one its not working.
**Here is my controller method **, for both adding and updating service
public function post(ServiceRequest $request, Service $service)
{
$service = Service::firstOrNew(['id' => $request->get('id')]);
$service->id = $request->get('id');
$service->name = $request->get('name');
$service->description = $request->get('description');
$image = $request->file('photo')->store('services/');
$service->photo = $image;
if ($request->hasFile('photo')) {
$image = $request->file('photo');
$name = time() . $service->name . '.' . $image->getClientOriginalExtension();
$destinationPath = public_path('/images/services');
$image->move($destinationPath, $name);
}
if ($request->has('photo')) {
$image = $request->file('photo');
}
$service->save();
Alert::success('Service Saved');
return redirect()->back();
// dd($service);
}
I need some assistance with updating the image and removing an old one that was added on update record.

Multiple Image Upload in Laravel tweak to add additional field

I have a need to upload multiple images. This code below works well. This is using Intervention Image plugin. I am trying to customise this code to add another field which is a ForeignKey value to the parent of this image model. $request has the value coming from form. How to save it along with images?
The value is:
$request('vehicle_id')
How can tweak the below method so as save includes this vehicle_id as well?
public function uploadImage(Request $request)
{
$request->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
//check if image exist
if ($request->hasFile('image')) {
$images = $request->file('image');
// create new directory for uploading image if doesn't exist
if( ! File::exists('images/'.auth()->user()->id)) {
$org_img = File::makeDirectory('images/'.auth()->user()->id, 0777, true);
}
// loop through each image to save and upload
foreach($images as $key => $image) {
//create new instance of Photo class
$newPhoto = new $this->photo;
//get file name of image and concatenate with 4 random integer for unique
$filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
//path of image for upload
$org_path = 'images/'.auth()->user()->id . $filename;
$newPhoto->image = 'images/'.auth()->user()->id.$filename;
//don't upload file when unable to save name to database
if ( ! $newPhoto->save()) {
return false;
}
// upload image to server
if ($org_img == true) {
Image::make($image)->fit(900, 500, function ($constraint) {
$constraint->upsize();
})->save($org_path);
}
}
}
return redirect('/home')->with('success','Images Uploaded');
}
I found solution
public function uploadImage(Request $request)
{
$request->validate([
'image' => 'required',
'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
'vehicle' => 'required'
]);
//check if image exist
if ($request->hasFile('image')) {
$images = $request->file('image');
// create new directory for uploading image if doesn't exist
if( ! File::exists('images/'.auth()->user()->id.'/')) {
$org_img = File::makeDirectory('images/'.auth()->user()->id.'/', 0777, true);
}
// loop through each image to save and upload
foreach($images as $key => $image) {
//create new instance of Photo class
$newPhoto = new $this->photo;
//get file name of image and concatenate with 4 random integer for unique
$filename = rand(1111,9999).time().'.'.$image->getClientOriginalExtension();
//path of image for upload
$org_path = 'images/'.auth()->user()->id.'/' . $filename;
$newPhoto->image = 'images/'.auth()->user()->id.'/' . $filename;
$newPhoto->vehicle = $request->input('vehicle');
//don't upload file when unable to save name to database
if ( ! $newPhoto->save()) {
return false;
}
// upload image to server
Image::make($image)->fit(900, 500, function ($constraint) {
$constraint->upsize();
})->save($org_path);
}
}
return redirect('/home')->with('success','Images Uploaded');

How to upload image in array input type

I want to upload image using protected function create(array $data){}
Below code is used for public function create(Request $request){}
public function create(Request $request)
{
$image = new Image();
if ($request->hasFile('image')) {
$dir = 'uploads/';
$extension = strtolower($request->file('image')->getClientOriginalExtension()); // get image extension
$fileName = str_random() . '.' . $extension; // rename image
$request->file('image')->move($dir, $fileName);
$image->image = $fileName;
}
$image->save();
return view('here');
}
}
I tried the following code but gets error
protected function create(array $data)
{
$dir = '/customer/images/';
$extension = strtolower($data['image']->getClientOriginalExtension()); // get image extension
$fileName = str_random() . '.' . $extension; // rename image
$data['image']->move($dir, $fileName);
$data['image'] = $fileName;
return Image::create([
'image' => $data['image'],
]);
}
I'm getting error. How can i upload image using array.

I want to delete the stored image while update new image

I want to delete the stored image while update new image
public function update($id)
{
$users = AdminLogin::find($id);
if(Input::hasFile('image_file'))
{
$file = Input::file('image_file');
$name = time() . '-' . $file->getClientOriginalName();
$file = $file->move(('uploads/images'), $name);
$users->image_file= $name;
}
$users->save();
return response()->json($users);
}
You can write this. This will solve your problem
public function update($id)
{
$users = AdminLogin::find($id);
if(Input::hasFile('image_file'))
{
$usersImage = public_path("uploads/images/{$users->image_file}"); // get previous image from folder
if (File::exists($usersImage)) { // unlink or remove previous image from folder
unlink($usersImage);
}
$file = Input::file('image_file');
$name = time() . '-' . $file->getClientOriginalName();
$file = $file->move(('uploads/images'), $name);
$users->image_file= $name;
}
$users->save();
return response()->json($users);
}
This will delete the previous image and update the new image
Well, the answer is technically incorrect. What if the save operation fails, since you have deleted that image the current record will not have an image anymore.
So to overcome this problem you can adjust your code like:
if(Input::hasFile('image_file'))
{
$file = Input::file('image_file');
$name = time() . '-' . $file->getClientOriginalName();
$file = $file->move(('uploads/images'), $name);
$users->image_file= $name;
}
$users->save();
if(Input::hasFile('image_file'))
{
$usersImage = public_path("uploads/images/{$users->image_file}"); // get previous image from folder
if (File::exists($usersImage)) { // unlink or remove previous image from folder
unlink($usersImage);
}
}

Resources