save an avatar in octobercms database after i modified it - laravel

after resizing the user avatar with intervention image ,i try to store it in the octobercms database like this code:
if (Input::hasFile('avatar')) {
$file= Input::file('avatar');
$filenamewithextension = $file->getClientOriginalName();
//get filename without extension
$filename = pathinfo($filenamewithextension, PATHINFO_FILENAME);
//get file extension
$extension = $file->getClientOriginalExtension();
//filename to store
$filenametostore = $filename.'_'.time().'.'.$extension;
Storage::put('public/profile_images/'. $filenametostore, fopen($file, 'r+'));
Storage::put('public/profile_images/thumbnail/'. $filenametostore, fopen($file, 'r+'));
//Resize image here
$thumbnailpath ='storage/app/public/profile_images/thumbnail/'.$filenametostore;
$img = Image::make($file->getRealPath());
$img->crop(request('w'), request('h'), request('x1'), request('y1'));
$img->save($thumbnailpath);
$user->avatar= $filenametostore;
}
i get this error:
The avatar must be an image.
C:\wamp643\www\october3\vendor\october\rain\src\Database\Traits\Validation.php line 340
i really don't know what to do ,i'm a beginner.
please help me!!

you are just setting file name you should set full path of image there.
Assuming you have already avatar attachment relation in user model
public $attachOne = [
'avatar' => ['System\Models\File']
];
replace
$user->avatar = $filenametostore;
with
$user->avatar = storage_path($thumbnailpath);
may be it should work.
if doubt please comment.

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.

Resize image and store it to s3

Default image upload process in my app like this.
Get image from request and store it to s3 and a local variable.
$path = $request->file("image")->store("images", "s3");
After this I make it public.
Storage::disk("s3")->setVisibility($path, 'public');
And store to DB like this.
$variable = ModelName::create([
"image" => basename($path),
"image_url" => Storage::disk("s3")->url($path),
But how to resize the image before store it to s3?
I try to write like this
$extension = $request->file('image')->getClientOriginalExtension();
$normal = Image::make($request->file('image'))->resize(160, 160)->encode($extension);
$filename = md5(time()).'_'.$request->file('image')->getClientOriginalName();
$img = Storage::disk('s3')->put('/images/'.$filename, (string)$normal, 'public');
And then
"image" => basename($filename ),
"image_url" => Storage::disk("s3")->url($img),
This works except one thing. I can't get URL (to store DB) for uploaded image.
How to get correct public url for uploaded image?
Note:I use Intervention Image package
Storage::put() would only return the path if it's an instance of File or UploadedFile (source). In this case $normal isn't, so put() would return a boolean instead. Also, using getClientOriginalExtension() probably isn't a good idea since it's not considered a safe value (source).
So here's a bit improved version:
$filename = $request->file('file')->hashname();
$image = Image::make($request->file('file'))->resize(160, 160);
Storage::disk('s3')->put('/images/'.$filename, $image->stream(), 'public');
$url = Storage::disk('s3')->url('/images/'.$filename);
You can now save $url and $filename into your db.
You can try my code snippet.
$file = $request->file('image');
$fileName = md5(time()).'.'.$file->getClientOriginalExtension();
/** #var Intervention $image */
$image = Image::make($file);
if ($image->width() > ($maxWidth ?? 500)) {
$image = $image->resize(500, null, function ($constraint) {$constraint->aspectRatio();});
}
$image = $image->stream();
try {
/** #var Storage $path */
Storage::disk('s3')->put(
$dir . DIRECTORY_SEPARATOR . $fileName, $image->__toString()
);
} catch (\Exception $exception) {
Log::debug($exception->getMessage());
}

unlink image only if exists in 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);

How to save formdata and this URL into the database .. I can upload the file to the cloudinary

Hiii , I have this formdata with few data and files. I want to store them into my database table.
this is my controller to store into the UserApplyJob model
public function store(Request $request)
{
$file = $request->file('resume');
Cloudder::upload($file->getRealPath(), null, ['resource_type' => 'raw']);
$publicId = Cloudder::getPublicId();
$url =Cloudder::show($publicId, ['resource_type' => 'raw']);
$requestJob = UserApplyJob::create($request->all());
}
You're not persisting it to the db. Try this at the end.
$requestJob->save();
This is from laravel 7.14
if($request->hasFile('cover_image'))
{
// Get the file with extension
$filenameWithExt = $request->file('cover_image')->getClientOriginalName();
//Get the file name
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
//Get the ext
$extension = $request->file('cover_image')->getClientOriginalExtension();
//File name to store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
}
// Save the image to column
$blog->cover_image = $fileNameToStore;

Store an image in October CMS database after resizing it with image intervention package

I try to store a user avatar in the October CMS database after resizing it with intervention image package I use this code:
if (Input::hasFile('avatar')) {
$file= $user->avatar;
$filenamewithextension = $file->getClientOriginalName();
//get filename without extension
$filename = pathinfo($filenamewithextension, PATHINFO_FILENAME);
//get file extension
$extension = $file->getClientOriginalExtension();
//filename to store
$filenametostore = $filename.'_'.uniqid().'.'.$extension;
Storage::put('public/profile_images/'. $filenametostore, fopen($file, 'r+'));
Storage::put('public/profile_images/thumbnail/'. $filenametostore, fopen($file, 'r+'));
//Resize image here
$thumbnailpath ='storage/app/public/profile_images/thumbnail/'.$filenametostore;
$img = Image::make($file->getRealPath());
$img->crop(request('w'), request('h'), request('x1'), request('y1'));
$img->save($thumbnailpath);
$user->avatar=$filenametostore;
}
but I get an error:
Call to undefined method October\Rain\Database\QueryBuilder::getClientOriginalName()
can anyone help me please?!
You are calling getClientOriginalName() on the wrong object, try changing the following lines in your code to this:
if (Input::hasFile('avatar')) {
$file = Input::file('avatar');
/* ... */
Storage::put('public/profile_images/'. $filenametostore, fopen($file->getRealPath(), 'r+'));
Storage::put('public/profile_images/thumbnail/'. $filenametostore, fopen($file->getRealPath(), 'r+'));
/* ... */
}

Resources