Save multiple upload with clientOriginalName - laravel

hy everyone,, i want to upload multiple file with OriginalClientName, save into database with column called "document" but when data saved into database the file when uploading is not same the name,, i am upload file with name "cv bimo.docx", but in database, the name like this:
C:\Users\bimo_an\AppData\Local\Temp\phpAAF.tmp
i already using method getClientOriginalName(),,
this is my Function controller code :
..............................
$uploadFile = $request->file('document');
foreach($uploadFile as $file){
$filename = $file->getClientOriginalName();
$folder[] = $file->storeAs('uploads', $filename);
}
$data = [
'mto_number'=>$request->txtDocNumber,
'item_code'=>$request->txtItemCode[$key],
'required_qty'=>$request->txtRequiredQty[$key],
'spare_qty'=>$request->txtSpareQty[$key],
// 'file' => $path[$key]
'category' => $request->category[$key],
'document' => $file
];
ModelMTOItem::insert($data);

You are passing file Path instead of clientOriginalName
$uploadFile = $request->file('document');
foreach($uploadFile as $file) {
$filename = $file->getClientOriginalName();
$data = [
'mto_number'=>$request->txtDocNumber,
'item_code'=>$request->txtItemCode[$key],
'required_qty'=>$request->txtRequiredQty[$key],
'spare_qty'=>$request->txtSpareQty[$key],
// 'file' => $path[$key]
'category' => $request->category[$key],
'document' => $filename
];
ModelMTOItem::insert($data);
$folder[] = $file->storeAs('uploads', $filename);
}

Related

Change directory for uploading image

How can I change the directory of the uploaded images.
I want to upload it in the App/public/files folder.
My code here:
public function update(Request $request, Organigramme $organigramme)
{
$id = $organigramme->id;
$organigramme = Organigramme::find($id);
$organigramme->matricule = $request->input('matricule');
if ($request->has('profile_image'))
{
$image = $request->file('profile_image');
$name = str_slug($request->input('matricule'));
$folder = '/uploads/images/';
$filePath = $folder . $name. '.' . $image->getClientOriginalExtension();
$this->uploadOne($image, $folder, 'public', $name);
$organigramme->profile_image = $filePath;
$organigramme->save();
}
return view( 'admin.organigrammes.show', compact('organigramme'));
}
public function uploadOne(UploadedFile $uploadedFile, $folder = null, $disk = 'public', $filename = null)
{
$name = !is_null($filename) ? $filename : str_random(25);
$file = $uploadedFile->storeAs($folder, $name.'.'.$uploadedFile->getClientOriginalExtension(), $disk);
return $file;
}
In the config/filesystems file add a new save path.For example:
'images' => [
'driver' => 'local',
'root' => base_path().'/app/public/files',
],
In the code itself, use the following code to save:
Storage::disk('images')->put($path, $image);

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);
}

How to delete old picture after new one uploaded

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.

updated image stores in database but not folder in laravel

problem is that company_photo stores in database but not store in company_photos folder, please tell me where i going wrong..
public function update(Request $request, Company $company,CompanyOtherInfo $CompanyOtherInfo )
{
//dd($company);
//dd(request()->all());
if($request->hasFile('company_photo')){
$files=public_path().'/company_photos/'.$req->input('company_photo1');
File::delete($files);
//dd($files);
$file = $req->file('company_photo');
$destinationPath = public_path().'/company_photos/';
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
// echo $filename;
}
else{
$filename=$request->input('company_photo1');
}
//dd($request);
//dd($filename);
$company::where('companies.company_id',$company->company_id)
->update([
'company_photo' => $filename,
'company_name' => request('company_name'),
'company_email' => request('company_email'),
'company_mobile' => request('company_mobile'),
'company_country' => request('company_country'),
'company_state' => request('company_state'),
'company_city' => request('company_city'),
'company_pincode' => request('company_pincode'),
'company_address' => request('company_address'),
'industry_id' => request('industry_id'),
'segment_id' => request('segment_id'),
'company_code' => request('company_code'),
'contact_person'=>request('contact_person'),
]);
The issue you had is you changed the variable $request to $req half way through your code:
Change these lines:
$files = public_path().'/company_photos/'.$req->input('company_photo1');
$file = $req->file('company_photo');
to:
$files = public_path().'/company_photos/'.$request->input('company_photo1');
$file = $request->file('company_photo');
Here is the code with a little refactor:
$filename = $request->input('company_photo1');
if ($request->hasFile('company_photo')) {
$files = public_path().'/company_photos/'.$fileName;
File::delete($files);
$file = $request->file('company_photo');
$file->move(public_path().'/company_photos/', $file->getClientOriginalName());
}

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