How to delete old picture after new one uploaded - laravel

I have this in my Controller which handles image upload
public function updateProfileImage(Request $request)
{
$user = auth('api')->user();
$image = $request->input('image'); // image base64 encoded
preg_match("/data:image\/(.*?);/",$image,$image_extension); // extract the image extension
$image = preg_replace('/data:image\/(.*?);base64,/','',$image); // remove the type part
$image = str_replace(' ', '+', $image);
$imageName = 'profile' . time() . '.' . $image_extension[1];
Storage::disk('public')->put($imageName,base64_decode($image));
$user->update($request->except('image') + [
'profilePicture' => $imageName
]);
return [
//'Message' => "Success",
'profilePhoto' => $user['profilePicture']
];
}
How can i delete the old picture from the directory after new one has been uploaded.

You can delete the image with Storage::delete() method (https://laravel.com/docs/7.x/filesystem#deleting-files). So, get the image before you update, then delete when it's ok to do:
$oldImage = $user->profilePicture;
Storage::disk('public')->put($imageName,base64_decode($image));
$user->update($request->except('image') + [
'profilePicture' => $imageName
]);
Storage::disk('public')->delete($oldImage);
return [
//'Message' => "Success",
'profilePhoto' => $user['profilePicture']
];
PS: I'm not sure if the profilePicture attribute is the same of your storage. Anyway, make any adjustment to match if needed.

Related

send file to an api using guzzle http client

after uploading an image in web system a i want to push the image to another web system b.i am using guzzle http client to push and save the image in system b.i have been able to save the image in system a but when it reaches the part to push and save to system b an error that i have set to show when there is an error on uploading the image.here is my function to save the image on system a
public function productSavePicture(Request $request)
{
try {
$validation = Validator::make($request->all(), [
'product_id' => 'required',
]);
if ($validation->fails()) {
throw new \Exception("validation_error", 19);
}
$product_details = product::where('systemid', $request->product_id)->first();
if (!$product_details) {
throw new \Exception('product_not_found', 25);
}
if ($request->hasfile('file')) {
$file = $request->file('file');
$extension = $file->getClientOriginalExtension(); // getting image extension
$company_id = Auth::user()->staff->company_id;
if (!in_array($extension, array(
'jpg', 'JPG', 'png', 'PNG', 'jpeg', 'JPEG', 'gif', 'GIF', 'bmp', 'BMP', 'tiff', 'TIFF'))) {
return abort(403);
}
$filename = ('p' . sprintf("%010d", $product_details->id)) . '-m' . sprintf("%010d", $company_id) . rand(1000, 9999) . '.' . $extension;
$product_id = $product_details->id;
$this->check_location("/images/product/$product_id/");
$file->move(public_path() . ("/images/product/$product_id/"), $filename);
$this->check_location("/images/product/$product_id/thumb/");
$thumb = new thumb();
$dest = public_path() . "/images/product/$product_id/thumb/thumb_" . $filename;
$thumb->createThumbnail(
public_path() . "/images/product/$product_id/" . $filename,
$dest,
200);
$systemid = $request->product_id;
$product_details->photo_1 = $filename;
$product_details->thumbnail_1 = 'thumb_' . $filename;
$product_details->save();
// push image to system on saving
$client = new \GuzzleHttp\Client();
$url = "http://systemb/api/push_image";
$response = $client->request('POST',$url,[
'headers' => [ ],
'multipart' => [
[
'name' => $filename,
'contents' => file_get_contents($product_details->getPath()),
],
],
]);
} else {
return abort(403);
}
} catch (\Exception $e) {
if ($e->getMessage() == 'validation_error') {
return '';
}
if ($e->getMessage() == 'product_not_found') {
$msg = "Error occured while uploading, Invalid product selected";
}
{
$msg = "Error occured while uploading picture";
}
$data = view('layouts.dialog', compact('msg'));
}
return $data;
}
i am getting the error "Error occured while uploading picture" but the error is saved in systema but its unabe to be pushed in systemb..i havent understood where i have gone wrong with my code base but i guess that part on guzzle isnt being executed because the data is being saved in systema but its unable to be pushed to systemb.what might be the issue here
Your class Product doesnt have the method getPath() declared
file_get_contents($product_details->getPath())
Change it so it uses the path you used above that line
file_get_contents(public_path() . "/images/product/$product_id/".$filename)

Sending an image with HTTP POST

Recently I wanted to separate my project in different services to I wanted to make blogs independent from the project.
In the first project i have written this code. I want to send the data that i get from the form to another API http://127.0.0.1:100/api/saveBlog
public function update(Request $request, $blog)
{
if (!$blog instanceof Blog) {
$blog = $this->getById($blog);
}
$response = Http::post("http://127.0.0.1:100/api/saveBlog",[
'name' => $request->input('name'),
'description' => $request->input('description'),
'name' => $request->input('name'),
'photto' => $request->file('photto')
]);
dd($response->status());
}
In the API service i am trying to read the data
Route::post("/saveBlog",function (Request $request){
$blog = new Blog();
$blog->name = $request->input('name');
$blog->description = $request->input('description');
$blog->name = $request->input('name');
$main = $request->file('photto');
$fileName = microtime() . '.' . $main->getClientOriginalExtension();
$img = Image::make($main->getRealPath());
$img->resize(400, 400);
$img->stream();
Storage::disk('local')->put('public/blogs/' . $fileName, $img, 'public');
$blog->image_path = "/storage/blogs/" . $fileName;
return $blog->save();
});
But i am getting 500 status error and blog is not being saved in database.
I think the problem is with $request->file('photto')
ANY IDEA?
check whether image exist in request like below
if($request->has('photto')){
$main = $request->file('photto');
$fileName = microtime() . '.' . $main->getClientOriginalExtension();
$img = Image::make($main->getRealPath());
$img->resize(400, 400);
$img->stream();
Storage::disk('local')->put('public/blogs/' . $fileName, $img, 'public');
$blog->image_path = "/storage/blogs/" . $fileName;
}
Updates
$photo = fopen(public_path('/storage/filename'), 'r');
$response = Http::
attach('photo', $photo)
->post($url, [
'param_1' => 'param_1 contents',
...
]);

Laravel I try to duplicate an object and add pictures in each object

I have a room to add. And there are fields called pieces. If the user has written all the fields, he chose pictures for the room. and wrote 5 pieces. I want to add 5 pieces to the same room with selected fields and photos. That is, duplicate the same object in several pieces.
RoomController store function
public function store(Request $request)
{
$request->validate([
'title.*' => 'required',
'content.*' => 'required',
'people' => 'required',
'hotel_id' => 'required',
'night_price' => 'required',
'pieces' => 'required',
'single_bed' => 'required',
'double_bed' => 'required',
'roomImages' => 'required',
'roomImages.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
]);
$rooms = array_fill(1, $request->get('pieces'), $request->all());
foreach ($rooms as $room){
dd($rooms);
$obj = new Room();
// Set translations
$obj->setTranslations('title', $room['title']);
$obj->setTranslations('content', $room['content']);
// Save object
$obj->amenities = $room['amenities'];
$obj->fill($room);
$obj->save();
foreach ($room['roomImages'] as $file) {
$file_name = time() . '_' . md5($file->getClientOriginalName()) . '.' . $file->getClientOriginalExtension();
$file->move(public_path('/uploads/rooms/'), $file_name);
// Save image in Model Image
$file = new Image();
$file->src = $file_name;
$obj->file()->save($file);
}
}
return redirect()->route('rooms.index');
}
Error
One circle of the foreach is running, the object with the pictures is added. On the 2nd lap, the foreach stops and shows this error
Try the bellow code
foreach ($request->roomImages as $file) {
$file_name = time() . '_' . md5($file->getClientOriginalName()) . '.' . $file->getClientOriginalExtension();
$file->move(public_path('/uploads/rooms/'), $file_name);
}
$rooms = array_fill(1, $request->get('pieces'), $request->all());
foreach ($rooms as $key => $room){
$obj = new Room();
// Set translations
$obj->setTranslations('title', $room['title']);
$obj->setTranslations('content', $room['content']);
// Save object
$obj->amenities = $room['amenities'];
$obj->fill($room);
$obj->save();
\File::copy(public_path('/uploads/rooms/'.$file_name), public_path('/uploads/rooms/'.$key.$file_name));
$file = new Image();
$file->src = $key.$file_name;
$obj->file()->save($file);
}
\File::delete(public_path('/uploads/rooms/'.$file_name));
The move function will delete the file from the original request. So when the loop run second time, you are getting error.
So your issue looks like you are overriding $file when creating your Image model.
foreach ($room['roomImages'] as $file) {
$file_name = time() . '_' . md5($file->getClientOriginalName()) . '.' . $file->getClientOriginalExtension();
$file->move(public_path('/uploads/rooms/'), $file_name);
// Save image in Model Image
// Updated variable name
$image = new Image();
$image->src = $file_name;
// save Model
$image->save();
$obj->file()->save($file);
}

laravel livewire intervention images

I am trying to use Intervention image with Livewire to reduce the sizes and I am not succeeding. They can guide me or tell me if Livewire may not allow it.
I am trying to pass this methodology:
foreach ($this->imagenes as $pathGaleria) {
$imgUrl = $pathGaleria->store('imagenesPropiedades');
$img = imgPropiedades::create([
'url' => $imgUrl,
'property_id' => $this->propiedadId
]);
to this other way:
foreach ($this->imagenes as $pathGaleria) {
$imgUrl = $pathGaleria->store('imagenesPropiedades');
Image::make($pathGaleria)->resize(1200, null, function ($constraint) {
$constraint->aspectRatio();
})
->save($imgUrl);
$img = imgPropiedades::create([
'url' => $imgUrl,
'property_id' => $this->propiedadId
]);
}
but the page remains blank. Thank you.
I found this today, may work for you
https://gist.github.com/daugaard47/659984245d31b895d00ee5dcbdee44ec
+
$images = Collection::wrap($request->file('file'));
$images->each(function ($image) use ($id) {
$basename = Str::random();
$original = $basename . '.' . $image->getClientOriginalExtension();
$thumbnail = $basename . '_thumb.' . $image->getClientOriginalExtension();
ImageManager::make($image)
->fit(250, 250)
->save(public_path('/images/' . $thumbnail));
$image->move(public_path('/images/'), $original);
Model::create([
]);
});

Image is not saved/updated into database using Laravel

I am trying to save my image into database while creating my user and i am using postman for this
My Code:
public function register(Request $request) {
$body = $request->all();
$userProfile = $body['user_profile'];
$userPrev = $body['privileges'];
$userProfile['is_super_admin'] = $userPrev['is_super_admin'];
$facilities = $userPrev['facilities'];
$bodyObj = array_merge($userProfile, $userPrev);
$validator = UserValidations::validateUser($bodyObj);
if ($validator->fails()) {
return response([
'status' => false,
'message' => __('messages.validation_errors'),
'errors' => $validator->errors()->all()
], 200);
}
DB::beginTransaction();
try {
If (Input::hasFile('image')) {
$file = Input::file('image');
$destinationPath = public_path() . '/profile_images/';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
$this->user->where('id', Auth::user()->id)->update(['profile_pic' => $filename]);
}
My user is created and saved into database, but the image is not.
Your help will be highly appreciated!
I am really confused. You want to store image in database (bad Idea). Secondly, You want to store image in database but you are storing the file name only.
Suggetion : If you would like to store images in database you have an option to convert it into base64 and store the string. While retrieving you could decode base64. For example:
$file = Input::file('image');
$img_data = file_get_contents($file);
$base64 = $base64_encode($img_data);
$this->user->where('id', Auth::user()->id)->update(['profile_pic' => $base64 ]);
Another suggetion [Best way] : store path in the database and store the file in the storage or public and use the url to access the image
However if you still want to save it on database
$image = addslashes(file_get_contents(Input::file('image')));
$this->user->where('id', Auth::user()->id)->update(['profile_pic' => $image ]);

Resources