Eloquent delete does not work - laravel

I need your help, delete doesn´t work.
public function postUnregisterPushNotifications()
{
try {
$serial_usr = JWTAuth::getPayload(JWTAuth::getToken())->get('sub');
$device_token = Input::get('device_token');
$topic = null;
$device = Device::where('user_id', $serial_usr)->where('token', $device_token);
$device-> delete();
JWTAuth::setToken(JWTAuth::getToken())->invalidate();
return ws_response(false, 'Unregister Notification success', '', 200);
} catch (Exception $ex) {
return ws_response(true, null, 'ERROR ' . $ex->getCode() . '! ' . $ex->getMessage(), 500);
}
}
The insert to the table works but the delete when I logout does not delete from the table

What you're missing here is the ->get() method which fetches from the database and then ->delete() method works on the selection.
This should be how your code snippet should look like.
public function postUnregisterPushNotifications()
{
try {
$serial_usr = JWTAuth::getPayload(JWTAuth::getToken())->get('sub');
$device_token = Input::get('device_token');
$topic = null;
$device = Device::where('user_id', $serial_usr)->where('token', $device_token)->get();
$device->delete();
JWTAuth::setToken(JWTAuth::getToken())->invalidate();
return ws_response(false, 'Unregister Notification success', '', 200);
} catch (Exception $ex) {
return ws_response(true, null, 'ERROR ' . $ex->getCode() . '! ' . $ex->getMessage(), 500);
}
}

Related

How to catch exception in parent control of class with findOrFail?

In Laravel 9 I make Repository class and in one of its methods I have with 2 findOrFail calling
use Illuminate\Database\Eloquent\ModelNotFoundException;
class ArticleToManyVotesRepository
...
public function store(int $id, int $manyItemId, array $data): JsonResponse|MessageBag
{
$article = Article::findOrFail($id);
$vote = Vote::findOrFail($manyItemId);
if ($article->votes()->where('vote_id', $manyItemId)->exists()) {
throw new CustomManyToManyItemException('Article "' . $id . '" with vote ' . $manyItemId . ' already exists');
}
DB::beginTransaction();
try {
$article->votes()->attach($manyItemId, $data);
DB::Commit();
} catch (\Exception $e) {
\Log::info(varDump($e->getMessage(), ' -1 STORE $e->getMessage()::'));
DB::rollback();
return sendErrorResponse($e->getMessage(), 500);
}
return response()->json(['result' => true], 201); // 201
}
In the parent controller I have try block with checks for ModelNotFoundException:
public function articleManyVotesStore(Request $request, int $articleId, int $voteId)
{
try {
$data = $request->only('article_id', 'active', 'expired_at', 'supervisor_id', 'supervisor_notes');
return $repository->store(id: $articleId, manyItemId: $voteId,
data: $data);
} catch (ModelNotFoundException $e) {
return response()->json(['message' => $e->getMessage()], 404);
}
} catch (CustomManyToManyItemException $e) {
return response()->json(['message' => $e->getMessage()], 500);
}
}
But as in store method there are 2 calling of "findOrFail" in which way can I catch a valid Exception of findOrFail ?
Seems findOrFail has no any parameters ?
Thanks!
one way is to compare exception model namespace like below
try {
$data = $request->only('article_id', 'active', 'expired_at', 'supervisor_id', 'supervisor_notes');
return $repository->store(id: $articleId, manyItemId: $voteId,
data: $data);
} catch (ModelNotFoundException $e) {
if($e->getModel() === Article::class){
//add your logic here
}elseif($e->getModel() === Vote::class){
//add your logic here
}
return response()->json(['message' => $e->getMessage()], 404);
}

Delete website in Magento can't delete store and store view

I have a controller extended from Mage_Adminhtml_System_StoreController, below is the action I overwrite:
public function deleteWebsitePostAction()
{
$multiWebEnable = Mage::getStoreConfig('web/multi_web_general/multi_web');
$itemId = $this->getRequest()->getParam('item_id');
if (!$model = Mage::getModel('core/website')->load($itemId)) {
$this->_getSession()->addError(Mage::helper('core')->__('Unable to proceed. Please, try again'));
$this->_redirect('*/*/');
return;
}
if (!$model->isCanDelete()) {
$this->_getSession()->addError(Mage::helper('core')->__('This website cannot be deleted.'));
$this->_redirect('*/*/editWebsite', array('website_id' => $model->getId()));
return;
}
$this->_backupDatabase('*/*/editWebsite', array('website_id' => $itemId));
try {
$model->delete();
if ($multiWebEnable) {
$websiteCode = $model->getCode();
$websiteDir = BP . DS . 'mpshop' . DS . $websiteCode;
if (is_dir($websiteDir)) {
$objects = scandir($websiteDir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($websiteDir . DS . $object) == "dir") {
rmdir($websiteDir . DS . $object);
} else {
unlink($websiteDir . DS . $object);
}
}
}
reset($objects);
rmdir($websiteDir);
}
}
$this->_getSession()->addSuccess(Mage::helper('core')->__('The website has been deleted.'));
$this->_redirect('*/*/');
return;
} catch (Mage_Core_Exception $e) {
$this->_getSession()->addError($e->getMessage());
} catch (Exception $e) {
$this->_getSession()->addException($e, Mage::helper('core')->__('Unable to delete website. Please, try again later.'));
}
$this->_redirect('*/*/editWebsite', array('website_id' => $itemId));
}
I tried to comment out this function in my controller but the issue still there.
I'm confused with this. I need to know why this can happens, give me some suggestion... THanks
Any help will be appreciated.
Well,
After research deep inside, I realise one foreign key was missing between core_website table and core_store, core_store_group.
The solution here is download Magento Database Repair Tool which available to download at Magento homepage.
Hope this help.
Note that deleting websites can only be done from admin panel which is why the standalone script has that.
( Placed in root/var folder )
This will delete your website from a standalone file:
require_once( 'app/Mage.php' );
umask(0);
Mage::app( 'admin' );
function deleteWebsitePostAction()
{
try
{
$sWebsiteId = 'a';
$oWebsite = Mage::getModel( 'core/website' )->load( $sWebsiteId );
if( !empty( $oWebsite->getId() ) )
{
$oWebsite->delete();
}
}
catch( Exception $oException )
{
Mage::logException( $oException );
}
}
deleteWebsitePostAction();
To implement this in the admin panel ensure that you are submitting the correct variable to the controller, in this case I chose the name website_id so your form should have an somewhere.
public function deleteWebsitePostAction()
{
try
{
$sWebsiteId = $this->getRequest()->getParam( 'website_id' );
$sWebsiteId = 'a';
$oWebsite = Mage::getModel( 'core/website' )->load( $sWebsiteId );
if( !empty( $oWebsite->getId() ) )
{
$oWebsite->delete();
}
else
{
$this->_getSession()->addError( 'Unable to proceed. Please, try again' );
$this->_redirect( '*/*/' );
return;
}
}
catch( Exception $oException )
{
Mage::logException( $oException );
$this->_getSession()->addError( 'Unable to delete website. Please, try again' );
}
}
Disable your cache from Admin> System> Cache management
Refresh your cache and check again.
You can also delete your cache from cache management or [root]/var/cache

ModX Revo: Get Current Webuser or Manager session

How can I get the the number of all logged webuser (or manager, but not all types together). Is it possible with ModX API? Or is it necessary to inspect the DB table modx_session - but how is "data" column to readable?
I want to show a user counter, who is online (like in a forum).
Look at code in https://github.com/modxcms/revolution/blob/master/manager/controllers/default/dashboard/widget.grid-online.php - this is what you want.
I will try to solve it myself. Kind of solution:
Write a plugin that track events and persist it in database or somewhere else: OnWebLogin and OnWebLogout. Then read the count of logged in users.
Created a db table "modx_weblogin_session" (manually) userid, timestamp.
Created a Plugin:
if (isset($modx) && isset($user)) {
$eventName = $modx->event->name;
$isBackend = ($modx->context->key == 'mgr') ? true : false;
$errorMsg = '';
$userId = $user->get('id');
$output = 'WebLoginCountSession-Plugin: ' . $eventName . ' user-id: ' . $userId;
$logout = function ($userId) {
global $modx;
//Custom Mysqli Class
if (MySQLiDB::isConnected()) {
$mysqli = MySQLiDB::getConnection();
if ($mysqli instanceof mysqli) {
try {
$sql = "DELETE FROM `modx_weblogin_session` WHERE userid = ?";
$prep_state = $mysqli->prepare($sql);
$prep_state->bind_param('i', $userId);
$prep_state->execute();
} catch (Exception $e) {
//$modx->log(modX::LOG_LEVEL_ERROR, ...)
}
}
}
};
$login = function ($userId) {
global $modx;
if (MySQLiDB::isConnected()) {
$mysqli = MySQLiDB::getConnection();
if ($mysqli instanceof mysqli) {
try {
$sql = "REPLACE INTO `modx_weblogin_session` (`userid`) VALUES (?)";
$prep_state = $mysqli->prepare($sql);
$prep_state->bind_param('i', $userId);
$prep_state->execute();
} catch (Exception $e) {
//$modx->log(modX::LOG_LEVEL_ERROR, ...)
}
}
}
};
if (!$isBackend && !empty($userId)) {
switch ($eventName) {
case ('OnWebLogin'):
$output .= ' - login';
$login($userId);
break;
case ('OnWebLogout'):
$output .= ' - logout';
$logout($userId);
break;
}
}
if ($debug === true) {
return $output . ' ' . $errorMsg;
}
}

Magento Saving Multiselect Value on Custom Model

I have create a custom model in Magento which can get to and edit in the admin. I'm having trouble dealing with array's however. When I go to save the model, the text field saves fine, but the multiselect field just saves as 'array' and I'm then unable to go and edit it.
I need to know how to save seperate row in databse not comma seprate .
Can anybody help with this? Any help much appreciated!!!
public function saveAction() {
if ($data = $this->getRequest()->getPost()) {
if(isset($_FILES['image']['name']) && $_FILES['image']['name'] != null) {
try {
/* Starting upload */
$uploader = new Varien_File_Uploader('image');
// Any extention would work
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
// Set the file upload mode
// false -> get the file directly in the specified folder
// true -> get the file in the product like folders
// (file.jpg will go in something like /media/f/i/file.jpg)
$uploader->setFilesDispersion(false);
// We set media as the upload dir
$path = Mage::getBaseDir('media') . DS.'magentothem/vendorlist'.DS ;
$uploader->save($path, $_FILES['image']['name'] );
} catch (Exception $e) {
}
//this way the name is saved in DB
$basepath=Mage::getBaseUrl().'media/magentothem/vendorlist/';
$basepath=str_replace("index.php/","",$basepath);
$data['image'] = '<img src="'.$basepath.$_FILES['image']['name'].'" width="150" height="100px" alt="" />';
}
**$data['productid'] = join("," ,$_POST['productid']);**
$model = Mage::getModel('vendorlist/vendorlist');
$model->setData($data)->setId($this->getRequest()->getParam('id'));
try {
if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
$model->setCreatedTime(now())
->setUpdateTime(now());
} else {
$model->setUpdateTime(now());
}
$model->save();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('vendorlist')->__('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('vendorlist')->__('Unable to find item to save'));
$this->_redirect('*/*/');
}
if you want separate rows in your table, I assume the the id column is not the PK.
In this case you could try:
$model = Mage::getModel('vendorlist/vendorlist');
$productIds = Mage::app()->getRequest()->getParam('productid');
foreach ($productIds as $productId) {
$model->setData($data)->setProductid($productId)->setId($this->getRequest()->getParam('id'));
try {
if ($model->getCreatedTime == NULL || $model->getUpdateTime() == NULL) {
$model->setCreatedTime(now())
->setUpdateTime(now());
} else {
$model->setUpdateTime(now());
}
$model->save();
//remove what is after, put it after the try/catch
} catch (Exception $e) {
//handle exception
}
}

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