same hash multiple images - php

Well, I want to create only one hash for multiple files i upload so all those files will have the same hash so i can load all of them at once using that hash, but the problem is that in the store function hash changes for every file and i want it to stay the same for that upload
public function store(Request $request)
{
$picture = '';
$hash = substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyz"), 0, 8);
if ($request->hasFile('images'))
{
$files = $request->file('images');
foreach($files as $file) {
$image = new Upload();
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His') .'.'. $extension;
$destinationPath = base_path() . '/public/storage';
$file->move($destinationPath, $picture);
$image->hash = $hash;
$image->file_name = $picture;
$image->path = '/storage/'.$picture;
$image->save($request->all());
return redirect('/a/'.$hash);
}
}
}

You can generate hash and place it in upload form hidden field. After upload just read $_POST['hash'] instead of generating it in store().

Related

Resize image and store in Storage folder

Why does not this work?
I want to change the size and save it in the storage folder.
public function store(Request $request)
{
$image = $request->file('image') ?? null;
if ($request->hasFile('image'))
{
$file = $request->file('image');
$name = time();
$extension = $file->getClientOriginalExtension();
$fileName = $name . '.' . $extension;
$imageResize = Image::make($file)->resize(600, 300)->save('images/blogs/'.$fileName);
$image = $file->storeAs('',$imageResize, 'public');
}
Blog::query()->create([
'image' => $image,
]);
return redirect()->route('admin.blogs.index');
}
I see this error
Images must be saved in this way
Please try this and if you want add time to the name of your image simply add it to the input image name.
About permission if you are an a production server please set storage directory permission to the 755 but if you are on a local windows machine check if your storage directory has not read-only attribute.
public function store(Request $request)
{
$image = $request->file('image') ?? null;
if ($request->hasFile('image'))
{
$image = $request->file('image');
$input['imagename'] = $request->file('image')->getClientOriginalName();
$destinationPath = public_path('storage/images/blogs/resized');
$img = Image::make($image->path());
$img->resize(600, 300, function ($constraint) {
$constraint->aspectRatio();
})->save($destinationPath.'/'.$input['imagename']);
$destinationPath = public_path('storage/images/blogs/fullSize');
$image->move($destinationPath, $input['imagename']);
}
Blog::query()->create([
'image' => $image,
]);
return redirect()->route('admin.blogs.index')->withSuccess('Image successfully uploaded!');
}

Failed to rename image and upload using storeAs in Laravel

I created a form to store article with an image , and generate a resized version as thumbnail from it.
I want the image to be renamed after the article slug and stored in the "public/img/articles-images " directory but i keep receiving : "Image source not readable" error
This is the image upload handler function in my controller :
private function handleRequest($request)
{
$data = $request->all();
if ($request->hasFile('image')) {
$image = $request->file('image');
$fileName = $request->slug;
$successUploaded = $image->storeAs('img/articles-images', $fileName);
if($successUploaded) {
$width = config('cms.image.thumbnail.width');
$height = config('cms.image.thumbnail.height');
$extension = $image->getClientOriginalExtension();
$thumbnail = str_replace(".{$extension}", "_thumb.{$extension}", $fileName);
Image::make('img/articles-images' . '/' . $fileName)
->resize($width, $height)
->save('img/articles-images' . '/' . $thumbnail);
}
$data['image'] = $fileName;
}
return $data;
}
storeAs() method, which receives the path, the file name, and the (optional) disk as its arguments :
$successUploaded = $request->file('image')->storeAs(
'images', $fileName
);
I solved it ! Apparently there was no need to storeAs() method at all , the new code is like below :
if ($request->hasFile('image')) {
$image = $request->file('image');
$fileName = $request->slug.'.' .$image->getClientOriginalExtension();
$destination = $this->uploadPath;
$successUploaded = $image->move($destination, $fileName);
// //

how to do code refactoring to reduce similar code in laravel?

Hello I am a newbie, I just started creating a project for quiz application.I have repeated code in my store and update
function,how can i reduce the duplication and write a cleaner code, any help will be appreciated
Thanks Nabeel
This is my store method
public function store(Quiz $quiz, QuestionRequest $request)
{
if($request->hasfile('image'))
{
$file=$request->file('image');
//Get File name with the extension
$fileWithExt = $file->getClientOriginalName();
//Get Just File Name
$filename = pathinfo($fileWithExt,PATHINFO_FILENAME);
//Get Just Extension
$extension = $file->getClientOriginalExtension();
//Filename to store
$nameoffile = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->move(public_path('images'),$nameoffile);
//$path = $file->storeAs('app/img/',$nameoffile);
$path = $nameoffile;
}
else
{
$path=null;
}
}
This is my update method
public function update(Quiz $quiz,QuestionRequest $request,Question $question)
{
if(is_null($question->imgpath))
{
if($request->hasfile('image'))
{
$file=$request->file('image');
//Get File name with the extension
$fileWithExt = $file->getClientOriginalName();
//Get Just File Name
$filename = pathinfo($fileWithExt,PATHINFO_FILENAME);
//Get Just Extension
$extension = $file->getClientOriginalExtension();
//Filename to store
$nameoffile = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->move(public_path('images'),$nameoffile);
$path = $nameoffile;
}
else
{
$path=null;
}
}
elseif(!empty($question->imgpath) && $request->hasfile('image'))
{
$file=$request->file('image');
$fileWithExt = $file->getClientOriginalName();
$filename = pathinfo($fileWithExt,PATHINFO_FILENAME);
$extension = $file->getClientOriginalExtension();
$nameoffile = $filename.'_'.time().'.'.$extension;
$path = $file->move(public_path('images'),$nameoffile);
$path = $nameoffile;
}
else
{
$path=$question->imgpath;
}
You can create a new trait or function in your model class and can use that in your controller . Like this
In your Quiz.php just create a new function called fileUpload()
php artisan fileUpload($data)
{
$file=$data;
//Get File name with the extension
$fileWithExt = $file->getClientOriginalName();
//Get Just File Name
$filename = pathinfo($fileWithExt,PATHINFO_FILENAME);
//Get Just Extension
$extension = $file->getClientOriginalExtension();
//Filename to store
$nameoffile = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->move(public_path('images'),$nameoffile);
$path = $nameoffile;
return $path;
}
And in your controller in store() and update() you can just do this
if(is_null($question->imgpath))
{
if($request->hasfile('image'))
{
$path = $quiz->fileUpload($request->file('image'));
}
else
{
$path=null;
}
}

Laravel 5.5 - multiple images upload

I have this function in my controller:
use File;
use Image; //image intervention library
...
public function upload(Request $request)
{
//make sure there is a folder in public with the username
$username = Auth::user()->name;
$folderpath = public_path('images/' . $username . '/');
File::makeDirectory($folderpath, $mode = 0777, true, true);
$files = $request->file;
if(!empty($files)):
foreach($files as $file):
$filename = 'post_' . time() . '.' . $file->getClientOriginalExtension();
$path = $folderpath . $filename;
Image::make($file)->resize(800,400)->save($path);
endforeach;
endif;
return 'success';
}
which only save the last image if I upload multiple.
and I tried:
public function upload(Request $request)
{
//make sure there is a folder in public with the username
$username = Auth::user()->name;
$folderpath = public_path('images/' . $username . '/');
File::makeDirectory($folderpath, $mode = 0777, true, true);
$files = $request->file;
if(!empty($files)):
foreach($files as $file):
$filename = 'post_' . time() . '.' . $file->getClientOriginalExtension();
$path = $folderpath . $filename;
$file->save($path);
endforeach;
endif;
return ''success;
}
which throw me error:
Method save does not exist.
I goggled and it seems like I did not instantiate it with model. But in this case, how can I instantiate it with model if it is just a direct file upload?
What is the best way for multiple images upload in laravel?
Update
After reading #kunal's answer, I managed to solve the issue by adding a unique number for the file name:
public function upload(Request $request)
{
//make sure there is a folder in public with the username
$username = Auth::user()->name;
$folderpath = public_path('images/' . $username . '/');
File::makeDirectory($folderpath, $mode = 0777, true, true);
$files = $request->file;
$count = 0;//<-- add a counter
if(!empty($files)):
foreach($files as $file):
$filename = 'post_' . time() . '_' . $count . '.' . $file->getClientOriginalExtension();//<-- add counter to the file name
$path = $folderpath . $filename;
Image::make($file)->resize(800,400)->save($path);
$count ++;//<-- increase the value
endforeach;
endif;
return 'success';
}
May be you are looking for this kind of stuff:-
if ($request->hasFile('files')) {
$files = $request->file('files');
foreach($files as $file){
$extension = $file->getClientOriginalExtension();
$fileName = str_random(5)."-".date('his')."-".str_random(3).".".$extension;
$folderpath = 'images'.'/';
$file->move($folderpath , $fileName);
}
}
<input type="file" id="gallery" name="files[]" multiple />
I am thinking u may missed this part
<input type="file" id="gallery" name="file[]" />
note the file[] it must be array otherwise it will only save the last image if upload multiple image
If u did ur html part correct, then use like this,
foreach ($file as $photo) {
$path = Storage::putFile('foldername', $photo);
}
try this code:
$files= Input::file('image');
$destinationPath= 'images';
$images=array();
foreach($files as $file){
$fullname= $file->getClientOriginalName();
$hashname = $fullname;
$upload_success =$file->move($destinationPath, $hashname);
$images[]=$fullname;
$has= implode(",",$images);
}
$modelname= new Modelname;
$modelname->image_attachment = $has;
$modelname->save();
and yout html page:
<input type="file" id="image" name="image[]" />
It is not that complicated.
As of larval 5.8 you can do this:
collect($request->images)->each(function ($image) {
return $image->store('images', 'public');
});
It puts images in images folder of public disk.

best way to do this im using resource and eloquent laravel 4

Any best way to do this will be gratefull
what this do is grab the input from a form and save it to the database.
public function update()
{
$file = Input::file('path');
$destinationPath = 'img/';
$filename = $file->getClientOriginalName();
// $extension =$file->getClientOriginalExtension();
$upload_success = Input::file('path')->move($destinationPath, $filename);
$photo = Photo::find($_POST['id']);
$photo->caption = $_POST['caption'];
$photo->path = $destinationPath . $filename;
$photo->save();
if( $upload_success ) {
return Redirect::to('photos/'.$_POST['id'].'/edit')->withInput()->with('success', 'Photo have been updated.');
} else {
return Response::json('error', 400);
}
}
this work just fine but i wonder if there a simplify way to do this like how i can get post data from the form send to update to update the photo information instead of me using the $_POST and get the id from the form parse into the update($id) ect. Thanks
You can use the Input class, instead of accessing the post directly.
I would probably re-write the function a little like this:
public function update()
{
$file = Input::file('path');
$destinationPath = 'img/';
$filename = $file->getClientOriginalName();
if( Input::file('path')->move($destinationPath, $filename) )
{
$photo = Photo::find(Input::get('id'));
$photo->caption = Input::get('caption');
$photo->path = $destinationPath . $filename;
$photo->save();
return Redirect::to('photos/'.$_POST['id'].'/edit')->withInput()->with('success', 'Photo have been updated.');
}
else
{
return Response::json('error', 400);
}
}
The other option is to extract some of this data directly into your Photo model, and do it in there.

Categories