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

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;

Related

How can I save image in subfolder using Amazon aws3 | Laravel

I am using aws to store my images and the code in the controller looks like this:
Storage::disk('3')->put($file->getClientOriginalName(), fopen($file, 'r+'), 'public');
The images are being saved in my local storage.
Now though, I want to be able to create a subfolder to keep the images organized.
For my case, it is registering a business. Therefore I want the images to be stored in a subfolder containing the appropriate business id. I tried this:
Storage::disk('3')->put($file->getClientOriginalName(), fopen($file, 'r+'), 'public/' . $business->id.
More about the controller is as follows:
$input = $request->all();
$files = isset($input['file']) ? $input['file'] : array ();
$business_names = json_decode($input['business_names'], true);
$business_details = json_decode($input['business_details']);
$share_amount = json_decode($input['share_amount'], true);
$entity = json_decode($input['entity'], true);
$directors = json_decode($input['directors'], true);
$shareholders = json_decode($input['shareholders'], true);
$appointments = json_decode($input['appointments'], true);
$input['user_id'] = Auth::user()->id;
Log::info(Auth::user());
Log::info($request->user());
/* Create Business Record */
$business = new Business;
$business->business_names = json_encode($business_names);
$business->share_amount = $share_amount ?: 0;
$business->entity = $entity ?: '';
$business->business_physical_address = json_encode($business_details->physical_address);
$business->has_business_postal_address = $business_details->has_postal_address;
$business->business_postal_address = json_encode($business_details->postal_address);
$business->user_id = $input['user_id'];
$business->save();
/* Create a new folder in storage/app/files named after the business ID */
Storage::makeDirectory('files/' . $business->id);
/* Upload Files */
// TODO: file storing?
foreach($files as $file) {
if ($file) {
Storage::disk('3')->put($file->getClientOriginalName(), fopen($file, 'r+'), 'public/' . $business->id);
// $file->storeAs('files/' . $business->id, $file->getClientOriginalName());
}
}
When I try to save a business now, I see the following error:
C:\xampp\htdocs\startingabandbaby\vendor\league\flysystem\src\Adapter\Local.php(356):
Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8,
'Undefined index...', 'C:\xampp\htdocs...', 356, Array)
Since I was able to store images before, I am assuming that it is something to do with concatenating the business id.
How can I create a subfolder with the business id everytime I create a new business and add all the files in that same folder?
As per our discussion, you can use below 2 solutions:
1) put():
$path = Storage::disk('s3')->put(
'/files/'. $business->id, //path you want to upload image to S3
file_get_contents($request->file('file')), //fileContent
'public' //visibility
2) putFileAs(): To achieve the same thing withputFileAs(), I needed to write it as below. 1st parameter expects the directory name, I left it blank as I'm mimicking the directory name in s3 through the filename.
$path = Storage::disk('s3')->putFileAs(
'', // 1st parameter expects directory name, I left it blank as I'm mimicking the directory name through the filename
'/files/'. $business->id,
$request->file('file'), //3rd parameter file resource
['visibility' => 'public'] //options
);
Hope this will helps you!
After some research I ended up with the following:
$directory = 'public/' . $business->id;
Storage::disk()->makeDirectory($directory);
foreach($files as $file) {
if ($file) {
Storage::disk()->put($directory . '/' .$file->getClientOriginalName(), fopen($file, 'r+'));
}
}

save an avatar in octobercms database after i modified it

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.

How to handle update on image upload

recently i'm trying to practice with laravel 5.5 and create simple upload and update image
here is my controller on store
$input = $request->all();
$this->validate($request, [
'photo' => 'sometimes|image|mimes:jpeg,png,jpg,gif,svg|max:500',
]);
if ($request->hasFile('photo')) {
$photo = $request->file('photo');
$ext = $photo->getClientOriginalExtension();
if ($request->file('photo')->isValid()) {
$photo_name = date('YmdHis'). ".$ext";
$photoName = time().'.'.$request->photo->getClientOriginalExtension();
$request->photo->move(public_path('photo-upload'), $photoName);
$upload_path = public_path('photo-upload');
$input['photo'] = $photoName;
}
}
controller update
if ($request->hasFile('photo')) {
// delete the old/previous one
$exist = Storage::disk('photo')->exists($student->photo);
if (isset($student->photo) && $exist) {
$delete = Storage::disk('photo')->delete($siswa->photo);
}
// upload new one
$photo = $request->file('photo');
$ext = $photo->getClientOriginalExtension();
$photoName = time().'.'.$request->foto->getClientOriginalExtension();
if ($request->file('photo')->isValid()) {
$upload_path = 'photo-upload';
$request->file('photo')->move($upload_path, $phptpName);
$input['photo'] = $iphotoName;
}
}
the store method works perfectly, it uploaded image to the right folder then update the databse
the problem is on the update, it update the database but it didn't upload the image to the photo-upload folder
Any suggestion?
Thanks

How to upload multiple images and store their name in database with laravel 5.1?

I have created a form for users can upload multiple images,and move uploaded images to 'Upload' folder and store their names in database. This is my code
public function multiple_upload() {
$multiupload = new Multiupload();
// getting all of the post data
$files = Input::file('images');
// Making counting of uploaded images
$file_count = count($files);
// start count how many uploaded
$uploadcount = 0;
foreach($files as $file) {
$rules = array('file' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
$validator = Validator::make(array('file'=> $file), $rules);
if($validator->passes()){
$destinationPath = 'uploads';
$filename = $file->getClientOriginalName();
$upload_success = $file->move($destinationPath, $filename);
$uploadcount ++;
$multiupload->fileimage = $filename;
$multiupload->save();
}
}
if($uploadcount == $file_count){
Session::flash('success', 'Upload successfully');
return Redirect::to('/');
}
else {
return Redirect::to('/')->withInput()->withErrors($validator);
}
}
After upload all images successfully move to 'Uploads' folder but, in database it store only one image name. So how to store all images name in database?
Please help me and thanks you for help.
The reason is that you are reusing the same Multiupload instance in your loop and just overwriting the saved name with the name of next file. You should be creating a new Multiupload instance for every file that gets uploaded.
As #edrzej.kurylo said
You have to add the below line to inside of foreach($files as $file) {
$multiupload = new Multiupload();
Because you are reusing the same Multiupload function again and again. You have to re initialize the Model for every time the loop runs.
You should move your $multiupload = new Multiupload(); into the foreach loop.
foreach($files as $file) {
$multiupload = new Multiupload();
}
I would use for loop in this manner:
if($request->hasFile('images'){
$files = $request->file('images');
for($i=0; $i<count($files); $i++){
$img = new SampleImage();
$name = rand().'.'.$files[$i]->getClientOriginalExtension();
$files[$i]->move('uploads/samples/',$name);
$img->image_name = $name;
$img->save();
}
}

how to encode image decoded by base64_decode, symfony

I have a image decode by base64_decode.
I have a entity Image. This is entity consist : id and path to the file. File of image load to server by this guide http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html.
How encode this string and upload file to server and upload path to database in controller.
my controller
public function updateattachmentAction()
{
$em = $this->getDoctrine()->getManager();
$photo = $em->getRepository('MyPluginBundle:Photo')->findOneById(4);
$str="";
$request = $this->container->get('request');
$image = $request->query->get('image');
// file_put_contents($photo, base64_decode($data));
// $photo->upload();
// $em->persist($photo);
// $em->flush();
$response = array("code" => 100,"success" => true);
//you can return result as JSON
return new Response(json_encode($response));
}
it should help DataUriNormalizer
https://symfony.com/blog/new-in-symfony-3-1-data-uri-normalizer## Heading ##
use Symfony\Component\Serializer\Normalizer\DataUriNormalizer;
$normalizer = new DataUriNormalizer();
$avatar = $normalizer->denormalize('data:image/gif;base64,R0lGODdhAQABAIAAAP///////ywAAAAAAQABAAACAkQBADs=', 'SplFileObject');
// $avatar is a SplFileObject with the GIF image contents
and this https://github.com/hshn/base64-encoded-file
use Hshn\Base64EncodedFile\HttpFoundation\File\Base64EncodedFile;
$file = new Base64EncodedFile(base64_encode($data));
$file->getPathname(); // "/path/to/file"
$file instanceof Symfony\Component\HttpFoundation\File\File; // true

Resources