How to Display Successful and Failed Data in Laravel Maatwebsites Import - laravel

In my Laravel-5.8 using Maatwebsites-3.1, I am trying to update Employee Leaves into MySQL database through MS Excel.
Controller
public function import(Request $request){
$request->validate([
'file' => 'required|max:10000|mimes:xlsx,xls',
]);
$path1 = $request->file('file')->store('temp');
$path=storage_path('app').'/'.$path1;
try{
Excel::import(new LeavesImport, $path);
} catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
$failures = $e->failures();
Log::error($e);
$errormessage = "";
foreach ($failures as $failure) {
$errormess = "";
foreach($failure->errors() as $error)
{
$errormess = $errormess.$error;
}
$errormessage = $errormessage." ,\n At Row ".$failure->row().", ".$errormess."<br>";
}
Session::flash('error', $errormessage);
return back();
}catch (\Illuminate\Database\QueryException $e)
{
$errorCode = $e->errorInfo[1];
if($errorCode == 1062){
Log::error($e);
DB::rollback();
Session::flash('error', 'You have a duplicate entry problem!');
}
return back();
}
Session::flash('success', 'Leave Records Imported Successfully');
return redirect()->back;
}
Below is the code for the data to be imported from the MS Excel Sheet
Import
class FirstLeaveSheetImport implements ToModel, WithHeadingRow, WithBatchInserts, WithValidation
{
protected $staffid, $leavetype, $commencementdate, $resumptiondate;
private $errors = []; // array to accumulate errors
use Importable;
return new HrLeaveRequest([
'employee_id' => $this->getStaffId(),
'leave_type_id' => $this->getLeaveType(),
'commencement_date' => $this->transformDate($row['commencement_date']),
'resumption_date' => $this->transformDate($row['resumption_date']),
'no_of_days' => $row['leave_days'],
]);
}
public function getStaffId(){
if(!empty($this->staffid)){
return HrEmployee::where('employee_code',$this->staffid)->where('company_id',Auth::user()->company_id)->pluck('id')->first();
} else {
return 0;
}
}
public function getLeaveType(){
if(!empty($this->leavetype) || !$this->leavetype){
return HrLeaveType::where('leave_type_name',$this->leavetype)->where('company_id',Auth::user()->company_id)->pluck('id')->first();
} else {
return 0;
}
}
// this function returns all validation errors after import:
public function getErrors()
{
return $this->errors;
}
public function transformDate($value, $format = 'Y-m-d')
{
try {
return \Carbon\Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value));
} catch (\ErrorException $e) {
return \Carbon\Carbon::createFromFormat($format, $value);
}
}
public function batchSize(): int
{
return 200;
}
public function headingRow(): int
{
return 1;
}
}
I want to display:
The List Successful uploads
The list of failed uploads
How do I achieve this?
Thanks

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);
}

Laravel Request validation 404 when data is invalid

I have trouble with Request validation in Laravel, when request data pass validation everything is ok but then data is invalid server response with 404
UserRequest
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'sometimes|required|unique:users,Name|min:5|max:30'
];
}
UserController
public function update(UserRequest $request, $id)
{
$token = JWTAuth::getToken();
$tokenData = JWTAuth::getPayload($token)->toArray();
if ($request->name != null) {
if (User::where('id', $tokenData['idUser'])->update(['Name' => $request->name])) {
$status = true;
} else {
$status = false;
}
}
return response()->json(['status' => $status]);
}
Try with this
public function update(UserRequest $request, $id)
{
$token = JWTAuth::getToken();
$tokenData = JWTAuth::getPayload($token)->toArray();
$validated = $request->validated();
if ($validated) {
if (User::where('id', $tokenData['idUser'])->update(['Name' => $request->name])) {
$status = true;
} else {
$status = false;
}
return response()->json(['status' => $status]);
}
else {
return redirect()->back()->withErrors($validated);
}
}
Hope this helps :)

Return false limits multiple error message to one?

On my multiple upload library, I have a set error function.
On my upload function I use a in_array to check file extensions. If the in_array detects error it displays multiple error messages correct.
The problem I am having is for some reason when I use return FALSE; under the $this->set_error('file_extension_not_allowed') then will on display one message. Not sure why return FALSE limits error messages.
Question: How is it possible to use my return false but be able to display multiple message correct.
<?php
class Multiple_upload {
public $set_errors = array();
public function __construct($config = array()) {
$this->CI =& get_instance();
$this->files = $this->clean($_FILES);
empty($config) OR $this->set_config($config);
}
public function set_config($config) {
foreach ($config as $key => $value) {
$this->$key = $value;
}
return $this;
}
public function upload($field = 'userfile') {
$allowed_extension = explode('|', $this->allowed_types);
if (empty($this->upload_path)) {
$this->set_error('upload_path_not_set', 'upload_path_check');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path)) {
$this->set_error('upload_path_in_correct', 'location_check');
return FALSE;
}
if (!empty($this->files[$field]['name'][0])) {
foreach ($this->files[$field]['name'] as $key => $value) {
$this->file_name = $this->files[$field]['name'][$key];
$get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($get_file_extension));
$array_1 = array(
$allowed_extension,
);
$array_2 = array(
$get_file_extension[1],
);
if (!in_array($array_2, $array_1)) {
$this->set_error('file_extension_not_allowed', 'extension_check');
return FALSE;
}
}
return $this;
}
}
public function set_error($message, $type) {
$this->CI->lang->load('upload', 'english');
$this->error_message[] = $this->CI->lang->line($message);
return $this;
}
public function display_error_messages($open_tag = '<p>', $close_tag = '</p>') {
foreach($this->error_message as $msg) {
var_dump($msg);
}
}
public function clean($data) {
if (is_array($data)) {
foreach ($data as $key => $value) {
unset($data[$key]);
$data[$this->clean($key)] = $this->clean($value);
}
} else {
$data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8');
}
return $data;
}
}
Maybe this can help...
public function upload($field = 'userfile')
{
$allowed_extension = explode('|', $this->allowed_types);
if (empty($this->upload_path))
{
$this->set_error('upload_path_not_set', 'upload_path_check');
return FALSE;
}
if (!realpath(FCPATH . $this->upload_path))
{
$this->set_error('upload_path_in_correct', 'location_check');
return FALSE;
}
if (!empty($this->files[$field]['name'][0]))
{
$check_error = 0;//added this
foreach ($this->files[$field]['name'] as $key => $value)
{
$this->file_name = $this->files[$field]['name'][$key];
$get_file_extension = explode('.', $this->files[$field]['name'][$key]);
$this->get_file_extension_end = strtolower(end($get_file_extension));
$array_1 = array(
$allowed_extension,
);
$array_2 = array(
$get_file_extension[1],
);
if (!in_array($array_2, $array_1))
{
$this->set_error('file_extension_not_allowed', 'extension_check');
$check_error++;
}
}
if($check_error > 0 )
{
return FALSE;
}
return $this;
}
}

Fatal error:Class 'Mage_Adminhtml_Controller_action' not found in BookmarksController.php on line 4

it shows:
Fatal error: Class 'Mage_Adminhtml_Controller_action' not found in .../app/code/local/Magentix/SocialBookmarking/controllers/Adminhtml/BookmarksController.php on line 4
I check it and find that nothing is in bookmarkscontroller.php.on line 4. What's wrong is it?
and I also check it that the social bookmarket plugin still shows in the front page here.
Original code:
<?php
/** http://www.magentix.fr **/
class Magentix_SocialBookmarking_Adminhtml_BookmarksController extends Mage_Adminhtml_Controller_action {
protected function _initAction() {
$this->loadLayout()
->_setActiveMenu('cms/socialbookmarking')
->_addBreadcrumb(Mage::helper('adminhtml')->__('Items Manager'), Mage::helper('adminhtml')->__('Item Manager'));
return $this;
}
public function indexAction() {
$this->_initAction()->renderLayout();
}
public function editAction() {
$id = $this->getRequest()->getParam('id');
$model = Mage::getModel('socialbookmarking/bookmarks')->load($id);
if ($model->getId() || $id == 0) {
$data = Mage::getSingleton('adminhtml/session')->getFormData(true);
if (!empty($data)) {
$model->setData($data);
}
Mage::register('socialbookmarking_data', $model);
$this->loadLayout();
$this->_setActiveMenu('cms/socialbookmarking');
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()->createBlock('socialbookmarking/adminhtml_bookmarks_edit'))
->_addLeft($this->getLayout()->createBlock('socialbookmarking/adminhtml_bookmarks_edit_tabs'));
$this->renderLayout();
} else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('socialbookmarking')->__('Bookmark does not exist'));
$this->_redirect('*/*/');
}
}
public function newAction() {
$this->_forward('edit');
}
public function saveAction() {
if ($data = $this->getRequest()->getPost()) {
if(isset($_FILES['bookmarkimage']['name']) && $_FILES['bookmarkimage']['name'] != '') {
try {
$uploader = new Varien_File_Uploader('bookmarkimage');
$uploader->setAllowedExtensions(array('jpg','jpeg','gif','png'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$path = Mage::getBaseDir('media').DS.'social';
$uploader->save($path, $_FILES['bookmarkimage']['name']);
} catch (Exception $e) {
}
$data['image'] = 'social/'.$_FILES['bookmarkimage']['name'];
}
if(isset($data['bookmarkimage']['delete'])) $data['image'] = '';
$model = Mage::getModel('socialbookmarking/bookmarks');
$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('socialbookmarking')->__('Bookmark 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('socialbookmarking')->__('Unable to find bookmark to save'));
$this->_redirect('*/*/');
}
public function deleteAction() {
if( $this->getRequest()->getParam('id') > 0 ) {
try {
$model = Mage::getModel('socialbookmarking/bookmarks');
$model->setId($this->getRequest()->getParam('id'))->delete();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('socialbookmarking')->__('Bookmark was successfully deleted'));
$this->_redirect('*/*/');
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
}
}
$this->_redirect('*/*/');
}
public function massDeleteAction() {
$socialbookmarkingIds = $this->getRequest()->getParam('socialbookmarking');
if(!is_array($socialbookmarkingIds)) {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('socialbookmarking')->__('Please select bookmark(s)'));
} else {
try {
foreach ($socialbookmarkingIds as $socialbookmarkingId) {
$socialbookmarking = Mage::getModel('socialbookmarking/bookmarks')->load($socialbookmarkingId);
$socialbookmarking->delete();
}
Mage::getSingleton('adminhtml/session')->addSuccess(
Mage::helper('adminhtml')->__(
'Total of %d record(s) were successfully deleted', count($socialbookmarkingIds)
)
);
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
}
}
$this->_redirect('*/*/index');
}
public function massStatusAction() {
$socialbookmarkingIds = $this->getRequest()->getParam('socialbookmarking');
if(!is_array($socialbookmarkingIds)) {
Mage::getSingleton('adminhtml/session')->addError($this->__('Please select bookmark(s)'));
} else {
try {
foreach ($socialbookmarkingIds as $socialbookmarkingId) {
$socialbookmarking = Mage::getSingleton('socialbookmarking/bookmarks')
->load($socialbookmarkingId)
->setStatus($this->getRequest()->getParam('status'))
->setIsMassupdate(true)
->save();
}
$this->_getSession()->addSuccess(
$this->__('Total of %d record(s) were successfully updated', count($socialbookmarkingIds))
);
} catch (Exception $e) {
$this->_getSession()->addError($e->getMessage());
}
}
$this->_redirect('*/*/index');
}
protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream') {
$response = $this->getResponse();
$response->setHeader('HTTP/1.1 200 OK','');
$response->setHeader('Pragma', 'public', true);
$response->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true);
$response->setHeader('Content-Disposition', 'attachment; image='.$fileName);
$response->setHeader('Last-Modified', date('r'));
$response->setHeader('Accept-Ranges', 'bytes');
$response->setHeader('Content-Length', strlen($content));
$response->setHeader('Content-type', $contentType);
$response->setBody($content);
$response->sendResponse();
die;
}
}
Your extended class name is misspelled - Mage_Adminhtml_Controller_action should be Mage_Adminhtml_Controller_Action.
Make sure you:
included the file in bookmarkscontroller.php
put BookMarksController is in the right place

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