Method break after calling function in same controller - laravel

I made a method that handles image. The problem is I want to call that method in my Edit method few times because there are 3 buttons for uploading image. But after calling my method for IMAGE the EDIT method just stops after first image. How can I stop that?
if($request->has('picture1')) {
return $this->upload_image($company, $asset, $request->picture1);
}
if($request->has('picture2')) {
return $this->upload_image($company, $asset, $request->picture2);
}
if($request->has('picture3')) {
return $this->upload_image($company, $asset, $request->picture2);
}
And this is my function for uploading image
public function upload_image($company, $asset, $image)
{
$filename = uniqid(rand());
$image = str_replace('data:image/png;base64,', '', $image);
$image = str_replace(' ', '+', $image);
if (!file_exists(public_path('/uploads/assets/pictures/' . $company->id . '/'))) {
File::makeDirectory(public_path('/uploads/assets/pictures/' . $company->id . '/'), 0777, true);
}
Image::make($image)->resize(1024, null, function ($constraint) { $constraint->aspectRatio();})
->save( public_path('/uploads/assets/pictures/' . $company->id . '/'. $filename ) );
}
How can i go back to my function after handling first image?

You have to simply remove the return keyword like this :
if($request->has('picture1')) {
$this->upload_image($company, $asset, $request->picture1);
}
if($request->has('picture2')) {
$this->upload_image($company, $asset, $request->picture2);
}
if($request->has('picture3')) {
$this->upload_image($company, $asset, $request->picture2);
}

Related

my image are not saved in upload folder in laravel

whenever I uploaded an image in laravel, the image is upload to the database but after database uploading, my image didn't save that image in my root folder,
here is my upload code:
public function store(Request $request)
{
$records = $request->all();
if ($records != '') {
if ($request->session()->has('is_user_logged')) {
$UserPostModel = new UserPostModel;
$UserPostModel->uid = $request->session()->get('uid');
$UserPostModel->uname = $request->session()->get('name');
$UserPostModel->msg = $request->input('status');
$UserPostModel->eid = $request->input('event');
if ($request->hasFile('image')) {
if ($request->file('image')->isValid()) {
$fileName = $request->file('image')->getClientOriginalName();
$fileName = time() . "_" . $fileName;
$request->file = move_uploaded_file('uploads',$fileName);
$UserPostModel->image = $fileName;
}
}
$UserPostModel->save();
return redirect('uprofile')->with('message', 'Seccessfully Post !');
} else {
return redirect('login');
}
} else {
return redirect('/uprofile')->with('message', 'Please select image!');
}
}
Use store method and pass the driver as the second argument
$path = $request->file('image')->store($store_path, 'public');
Please replace this code with your image upload condition.
if ($file = $request->file('image')) {
$name = time() . $file->getClientOriginalName();
$file->move('uploads', $name);
$UserPostModel->image = $name;
}
$UserPostModel -> save();

how to update image when i have my function

I'm having problem with this code in update photo:
I already have function on it but it doesnt work
if (isset($request['image'])) {
$image = request()->file('image')->move("pictures/{$users[0]['username']}", 'public');
}
if (isset($request['licenseimage_front'])) {
$request['licenseimage_front'] = request()->file('licenseimage_front')->store("licensepicture/front/{$users[0]['username']}", 'public');
}
if (isset($request['licenseimage_back'])) {
$request['licenseimage_back'] = request()->file('licenseimage_back')->store("licensepicture/back/{$users[0]['username']}", 'public');
}

Receive function fails to get image

I am working on multiple file upload code is not showing any error
public function imagenewAction()
{
$form = new ImageNewForm();
$form->get('submit')->setValue('Submit');
$request = $this->getRequest();
// die('checko');
if($request->isPost())
{
// die('checko');
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('file');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
$form->setData($data);
if ($form->isValid())
{
//New Code
$dataNew=array('','image','image1');
for($i=1;$i<=2;$i++)
{
$addressProof = $data[$dataNew[$i]]['name'];
$addressProofextension = pathinfo($addressProof, PATHINFO_EXTENSION);
// $addressProofimg = $addressProof . $i . "." . $addressProofextension;
$addressProofimg = $addressProof;
//$verificationdocuments->setdocphotocopy($addressProofimg);
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setDestination('public/img/upload');
$adapter->addFilter(new \Zend\Filter\File\Rename(array(
'target' => 'public/img/upload',
'overwrite' => true
)), null, $addressProofimg);
if(!$adapter->receive($addressProofimg))
{
print_r ( $adapter->getMessages (), 1 );
}
else
{
echo "Image Uploaded";
}
}
}
}
return array('form' => $form);
}
It is giving blank error messages and not uploading images please help me to get away with this I am stuck from last 2 days

Laravel, Fetching image from public/uploads folder

Controller :
public function index()
{
if (!file_exists("uploads/profiles/".\Auth::User()->id.".jpeg")) {
$image_content = File::get("uploads/profiles/default.jpg");
$image = response($image_content, 200)->header('Content-Type', 'image/jpeg');
$size = getimagesize($image);
$aspectratio = $size[0]/$size[1];
$img_thumbnail = Image::make($image)->resize(50*$aspectratio,50);
$img_profile = Image::make($image)->resize(160*$aspectratio,160);
$imgname = \Auth::User()->id;
$img_thumbnail->save('uploads/thumbnails/'.$imgname.".jpeg");
$img_profile->save('uploads/profiles/'.$imgname.".jpeg");
}
Error : : failed to open stream: No such file or directory.
Actually, I want to fetch the default.jpg image and save it to two other folders with different extension.
if( !file_exists('uploads/thumbnails/'. $folder)){
#mkdir('uploads/thumbnails/'. $folder, 0755);
}
if( !file_exists('uploads/profiles/'. $folder)){
#mkdir('uploads/profiles/'. $folder, 0755);
}
$img = 'uploads/profiles/'. \Auth::User()->id. '.jpeg';
if ( !file_exists($img)){
$save_extension = '.jpeg';
Image::make($img)
->resize(50, null, function ($constraint) {
$constraint->aspectRatio();
})->save('uploads/thumbnails/' . \Auth::User()->id . $save_extension);
Image::make($img)
->resize(160, null, function ($constraint) {
$constraint->aspectRatio();
})->save('uploads/profiles/' . \Auth::User()->id . $save_extension);
}
http://image.intervention.io/api/resize
public function index()
{
if (!file_exists("uploads/profiles/".\Auth::User()->id.".jpeg")) {
$image = File::get("uploads/profiles/default.jpg");
return response($image)->header('Content-Type', 'image/jpeg');
}
Make sure you're have the right permission to uploads/profiles/
chmod -R 777 /uploads/profiles/

Magento: Adminhtml form “Image” Field

I have set an input field of type “Image” in an admin form using the code below:
<?php
// Tab Form
// File: app/code/local/MyCompany/Mymodule/Block/Adminhtml/Items/Edit/Tab/Form.php
class MyCompany_Mymodule_Block_Adminhtml_Items_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
{
protected function _prepareForm()
{
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('mymodule_form', array('legend'=>Mage::helper('mymodule')->__('Item information')));
$fieldset->addField('photo', 'image', array(
'label' => Mage::helper('mymodule')->__('Photo'),
'required' => false,
'name' => 'photo',
));
if ( Mage::getSingleton('adminhtml/session')->getMymoduleData() )
{
$form->setValues(Mage::getSingleton('adminhtml/session')->getMymoduleData());
Mage::getSingleton('adminhtml/session')->setMymoduleData(null);
} elseif ( Mage::registry('mymodule_data') ) {
$form->setValues(Mage::registry('mymodule_data')->getData());
}
return parent::_prepareForm();
}
}
And then, inside the controller save the image using:
public function saveAction()
{
if($data = $this->getRequest()->getPost()) {
$model = Mage::getModel('mymodule/speakers');
$model->setData($data)->setId($this->getRequest()->getParam('id'));
$model->setKeynote($this->getRequest()->getParam('keynote'));
// Save photo
if(isset($_FILES['photo']['name']) && $_FILES['photo']['name'] != '') {
try {
$uploader = new Varien_File_Uploader('photo');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
// Set media as the upload dir
$media_path = Mage::getBaseDir('media') . DS;
// Upload the image
$uploader->save($media_path, $_FILES['photo']['name']);
$data['photo'] = $media_path . $_FILES['photo']['name'];
}
catch (Exception $e) {
print_r($e);
die;
}
}
else {
if(isset($data['photo']['delete']) && $data['photo']['delete'] == 1) {
$data['photo'] = '';
}
else {
unset($data['photo']);
}
}
if(isset($data['photo'])) $model->setPhoto($data['photo']);
try {
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('mymodule')->__('Item was successfully saved'));
Mage::getSingleton('adminhtml/session')->setFormData(false);
if ($this->getRequest()->getParam('back')) {
$this->_redirect('*/*/edit', array('id' => $model->getId()));
return;
}
$this->_redirect('*/*/');
return;
}
catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFormData($data);
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
return;
}
}
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('mymodule')->__('Unable to find item to save'));
$this->_redirect('*/*/');
}
Long story short: When I save the item (using Save or Save and Continue Edit) in backend it saves well one time. Then the next time it gives the next error:
Notice: Array to string conversion in
/home/wwwadmin/public_html/aaa.bbb.ccc/public/lib/Zend/Db/Statement/Pdo.php
on line 232
The next saves ok. The next: error. The next ok… You know what I mean…
I was looking some code to see how this input type is used. But nothing yet. Neither inside the magento code. This is the only thing I’ve found: http://www.magentocommerce.com/wiki/how_to/how_to_create_pdf_upload_in_backend_for_own_module
Any ideas?
Thanks
When this line is runs:
$model->setData($data)->setId($this->getRequest()->getParam('id'));<br/>
$model->_data['image'] will be set to array('image'=>'[YOUR path]')<br/>
you should call method setData() after all manipulations with data['image'];
Try below code for save action in your controller
if ($data = $this->getRequest()->getPost()) {
$id = $this->getRequest()->getParam('id');
$model = Mage::getModel('your_model')->load($id);
if (isset($data['image']['delete'])) {
Mage::helper('your_helper')->deleteImageFile($data['image']['value']);
}
$image = Mage::helper('your_helper')->uploadBannerImage();
if ($image || (isset($data['image']['delete']) && $data['image']['delete'])) {
$data['image'] = $image;
} else {
unset($data['image']);
}
$model->setData($data)
->setId($id);
try {
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess('Your request Save.');
$this->_redirect('*/*/');
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setFormData($data);
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
return;
}
} else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('your_helper')->__('Unable to find your request to save'));
$this->_redirect('*/*/');
}
In your helper
public function uploadBannerImage() {
$path = Mage::getBaseDir('media') . DS . 'images';
$image = "";
if (isset($_FILES['image']['name']) && $_FILES['image']['name'] != '') {
try {
/* Starting upload */
$uploader = new Varien_File_Uploader('image');
// Any extention would work
$uploader->setAllowedExtensions(array(
'jpg', 'jpeg', 'gif', 'png'
));
$uploader->setAllowRenameFiles(true);
$uploader->setFilesDispersion(true);
$uploader->save($path, $uploader->getCorrectFileName($_FILES['image']['name']));
$image = substr(strrchr($uploader->getUploadedFileName(), "/"), 1);
} catch (Exception $e) {
Mage::getSingleton('customer/session')->addError($e->getMessage());
}
}
return $image;
}
public function deleteImageFile($image) {
if (!$image) {
return;
}
try {
$img_path = Mage::getBaseDir('media') . "/" . $image;
if (!file_exists($img_path)) {
return;
}
unlink($img_path);
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}

Resources