Image is not saved/updated into database using Laravel - 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 ]);

Related

Laravel save tmp files

I changed the image upload directory to the public folder, but why is the file uploaded to the database on the tmp path? I want the record name in the database to match the file name. Can anyone help?
Controller (store method)
public function store(Request $request)
{
$validatedData = $request->validate([
'banner_title' => 'required|max:255',
'image' => 'image|file|max:5120',
]);
$imageName = time() . '.' . $request->image->extension();
$request->image->move(public_path('images/banner-image'), $imageName);
Banner::create($validatedData);
return redirect('/dashboard/banner')->with('msg', 'Success!');
}
Here is the solution,
Add below statement before the Banner::create($validatedData);
$validatedData['image'] = $imageName;
In here we can assign validated image to $imageName after that we can save it in database.

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.

How to image upload into databae using laravel?

I am trying to upload an image into the database but unfortunately not inserting an image into the database how to fix it, please help me thanks.
database table
https://ibb.co/3sT7C2N
controller
public function Add_slider(Request $request)
{
$this->validate($request, [
'select_image' => 'required'
]);
$content = new Sliders;
if($request->file('select_image')) {
$content->slider_image = Storage::disk('')->putFile('slider', $request->select_image);
}
$check = Sliders::create(
$request->only(['slider_image' => $content])
);
return back()
->with('success', 'Image Uploaded Successfully')
->with('path', $check);
}
You should do with the following way:
public function Add_slider(Request $request)
{
$this->validate($request, [
'select_image' => 'required'
]);
$image = $request->file('select_image');
$extension = $image->getClientOriginalExtension();
Storage::disk('public')->put($image->getFilename().'.'.$extension, File::get($image));
$content = new Sliders;
if($request->file('select_image'))
{
$content->slider_image = $image->getFilename().'.'.$extension;;
$content->save();
$check = Sliders::where('id', $content->id)->select('slider_image')->get();
return back()->with('success', 'Image Uploaded Successfully')->with('path',$check);
}
}
And in view blade file:
<img src="{{url($path[0]->slider_image)}}" alt="{{$path[0]->slider_image}}">
This returns only the filename:
Storage::disk('')->putFile('slider', $request->select_image);
Use this instead:
Sliders::create([
'slider_image' => $request->file('select_image')->get(),
]);
Make sure the column type from database is binary/blob.

Save multiple upload with clientOriginalName

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

Laravel Spark upload profile picture to external driver

I want to override the way Laravel Spark save the profile picture of a user to use an external driver such as S3 for example. I already have my S3 config for the bucket I want to use. What would be the best way to do this? Should I use a completely different route and use a custom endpoint or is there a config somewhere I could change so that Spark uses a different driver?
So ended up doing this
I added these methods in update-profile-photo.js
methods: {
updateProfilePhoto() {
axios.post('/settings/profile/details/profile-picture', this.gatherFormData())
.then(
() => {
console.log('Profile picture updated');
Bus.$emit('updateUser');
self.form.finishProcessing();
},
(error) => {
self.form.setErrors(error.response.data.errors);
}
);
},
gatherFormData() {
const data = new FormData();
data.append('photo', this.$refs.photo.files[0]);
return data;
}
}
And my Controller looked like this
public function updateProfilePicture(Request $request)
{
$this->validate($request, [
'photo' => 'required',
]);
// Storing the photo
//get filename with extension
$filenamewithextension = $request->file('photo')->getClientOriginalName();
//get filename without extension
$filename = pathinfo($filenamewithextension, PATHINFO_FILENAME);
//get file extension
$extension = $request->file('photo')->getClientOriginalExtension();
//filename to store
$filenametostore = $filename.'_'.time().'.'.$extension;
Storage::disk('s3_users')->put($filenametostore, fopen($request->file('photo'), 'r+'), 'public');
$url = $filenametostore;
$request->user()->forceFill([
'image_url' => $url
])->save();
return response()->json(
array(
"message" => "Profile picture was updated!",
)
);
}

Resources