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

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

Related

How to Display Successful and Failed Data in Laravel Maatwebsites Import

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

How to use JWT for laravel API for different user tables?

These are the basic functions of the driver user.
public function authenticate(Request $request){
$credentials=$request->only('email','password');
try {
\Config::set('auth.providers.users.model', \App\Driver::class);
\Config::set('auth.providers.users.table', 'drivers');
\Config::set('jwt.user', \App\Driver::class);
if (!$token =JWTAuth::attempt($credentials)) {
return response()->json(['error'=>'Invalid_Crendals'],401);
}
} catch (JWTException $e) {
return response()->json(['error' => 'could_not_create_token'], 500);
}
return response()->json(['token Login Driver'=>compact('token'),'msg'=>'driver']);
}
public function register(){
$email=request()->email;
$name=request()->name;
$last=request()->last;
$password=request()->password;
$driver=Driver::create([
'name'=>$name,
'email'=>$email,
'last'=>$last,
'password'=>bcrypt($password),
]);
\Config::set('auth.providers.users.model', \App\Driver::class);
\Config::set('auth.providers.users.table', 'drivers');
\Config::set('jwt.user', \App\Driver::class);
$token=JWTAuth::fromUser($driver);
return response()->json(['token Driver'=>$token],200);
}
public function testd(){
try {
\Config::set('auth.providers.users.model', \App\Driver::class);
\Config::set('auth.providers.users.table', 'drivers');
\Config::set('jwt.user', \App\Driver::class);
$token=JWTAuth::getToken();
$driver=JWTAuth::toUser($token);
} catch (JWTException $e) {
return response()->json(['error' => 'could_not_create_token'], 500);
}
return response()->json($driver);
}
These are the conventional user functions
public function authenticate(Request $request){
$credentials=$request->only('email','password');
try {
\Config::set('auth.providers.users.model', \App\User::class);
\Config::set('auth.providers.users.table', 'users');
\Config::set('jwt.user', \App\User::class);
if (!$token =JWTAuth::attempt($credentials)) {
return response()->json(['error'=>'Invalid_Crendals'],401);
}
} catch (JWTException $e) {
return response()->json(['error' => 'could_not_create_token'], 500);
}
return response()->json(['toke Login User'=>compact('token'),'msg'=>'User Register']);
}
public function register(){
$email=request()->email;
$name=request()->name;
$password=request()->password;
$user=User::create([
'name'=>$name,
'email'=>$email,
'password'=>bcrypt($password),
]);
\Config::set('auth.providers.users.model', \App\User::class);
\Config::set('auth.providers.users.table', 'users');
\Config::set('jwt.user', \App\User::class);
$token=JWTAuth::fromUser($user);
return response()->json(['token'=>$token],200);
}
public function testd(){
try {
\Config::set('auth.providers.users.model', \App\User::class);
\Config::set('auth.providers.users.table', 'users');
\Config::set('jwt.user', \App\User::class);
$token=JWTAuth::getToken();
$driver=JWTAuth::toUser($token);
} catch (JWTException $e) {
return response()->json(['error' => 'could_not__User_create_token'], 500);
}
return response()->json($driver);
}
And used a middleware for each one This is for the driver user
public function handle($request, Closure $next)
{
try {
Config::set('jwt.user','App\Driver');
Config::set('auth.providers.users.model', \App\Driver::class);
$user=JWTAuth::parseToken()->authenticate();
if (! $user) {
return response()->json(['user_not_found'], 404);
}
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
}
return $next($request);
}
And for the conventional user
try {
Config::set('jwt.user','App\User');
Config::set('auth.providers.users.model', \App\User::class);
if (! $user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['user_not_found'], 404);
}
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
}
return $next($request);
}
File App.php
Route::post('authenticate','Api\UserController#authenticate');
Route::post('register','Api\UserController#register');
Route::post('authenticate/driver','Api\DriverController#authenticate');
Route::post('register/driver','Api\DriverController#register');
Route::post('test/driver','Api\DriverController#testd')->middleware('driver');
Route::post('test/user','Api\UserController#testd')->middleware('user');
Users are authenticated and register well in their corresponding tables The problem I encounter is the following, When I use the generated token when registering a user Driver and I use this same token to access the route test / user where by logic this does not owe me To show no result since it is an incorrect token generated by another user, this same token enters the function and shows me the data of a conventional user. How can I solve this security problem? The truth has been many days and I have not been able to solve it.

How to get ID of authorized user in jwt-auth?

How to get ID of authorized user in jwt-auth?
I tried to get id by standart method, but it does not work
When using jwt-auth you can get the user ID by parsing the JWT token:
public function getAuthenticatedUser()
{
try {
if (! $user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['user_not_found'], 404);
}
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
}
$userId = $user->id;
# code...
}

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