How to call Laravel helper method in Config/Constants.php - laravel

I am giving this error
Call to undefined function getDefaultConfigByHost()
In constants.php line 5:
In helper.php
function getDefaultConfigByHost($developmentValue = null, $testValue = null,
$productionValue = null)
{
try {
if (! isset($_SERVER['HTTP_HOST'])) {
return null;
}
$domain = $_SERVER['HTTP_HOST'];
switch ($domain) {
case 'xxx.gglemd.com':
return $developmentValue;
case '192.168.1.18:8001':
return $testValue;
case 'yyy.service.com':
return $productionValue;
default:
return '';
}
} catch (Exception $exception) {
return '';
}
}
In constants.php
<?php
return [
'api' => [
'base' => env('API_BASE', getDefaultConfigByHost(),
'sfile_base' => env('SXFILE_API_BASE', getDefaultConfigByHost('')),
'private_key' => env('API_REQUEST_PRIVATE_KEY', 'bn-sjaddasdsadsadasdas'),
],
];

Related

do not show the success message if the data hasnt been updated n a form laravel

i have a form whereby on updating the data and storing it to the database it shows a success message.if one of the inputs isn't filled it shows an error.am getting a bug whereby when i want to re-update the data and i open the form with the existing inputs when i click save the data should just redirect back to the previous page and not show the success message as the data hasnt being updated.how can i achieve this,am looking for a logic here fellow devs..here is my update function code
public function update(Request $request)
{
try {
$validation = Validator::make($request->all(), [
'systemid' => 'required',
'category' => 'required',
'subcategory' => 'required',
'prdcategory' => 'required',
'prdbrand' => 'required'
]);
Log::debug('Request: '.json_encode($request->file()));
if ($validation->fails()) {
throw new \Exception("validation_error", 19);
}
$systemid = $request->systemid;
$product_details = product::where('systemid', $systemid)->first();
$changed = false;
if ($request->has('product_name')) {
if ($product_details->name != $request->product_name) {
$product_details->name = $request->product_name;
$changed = true;
}
}
if ($request->has('category')) {
if ($product_details->prdcategory_id != $request->category) {
$product_details->prdcategory_id = $request->category;
$changed = true;
}
}
if ($request->has('subcategory')) {
if ($product_details->prdsubcategory_id != $request->subcategory) {
$product_details->prdsubcategory_id = $request->subcategory;
$changed = true;
}
if ($product_details->ptype == 'voucher') {
$voucher = voucher::where('product_id', $product_details->id)->first();
if($voucher->subcategory_id != $request->subcategory){
$voucher->subcategory_id = $request->subcategory;
$voucher->save();
$changed = true;
}
}
}
if ($request->has('prdcategory')) {
if ($product_details->prdprdcategory_id != $request->prdcategory) {
$product_details->prdprdcategory_id = $request->prdcategory;
$changed = true;
}
}
if ($request->has('prdbrand')) {
if ($product_details->brand_id != $request->prdbrand) {
$product_details->brand_id = $request->prdbrand;
$changed = true;
}
}
if ($request->has('description')) {
if ($product_details->description != $request->description) {
$product_details->description = $request->description;
$changed = true;
}
}
if ($changed == true || true) {
$product_details->save();
$msg = "Product information updated successfully";
$data = view('layouts.dialog', compact('msg'));
//i have added this code but it doesnt work
} else if($changed == false) {
return back();
$data = '';
}
}
return $data;
}
my laravel project version is 5.8
The following line will always evaluate to True
$changed == true || true
And you have a catch statement missing at the end so I had to add it.
And I advise you to simply get the dirty version of $product_details.
You can use $product_details->isDirty() // boolean.
Or even better way is to use $product_details->wasChanged() // boolean
Here is the code after some tweaks:
public function update(Request $request)
{
try {
$validation = Validator::make($request->all(), [
'systemid' => 'required',
'category' => 'required',
'subcategory' => 'required',
'prdcategory' => 'required',
'prdbrand' => 'required'
]);
Log::debug('Request: '.json_encode($request->file()));
if ($validation->fails()) {
throw new \Exception('validation_error', 19);
}
$systemid = $request->systemid;
$product_details = Product::where('systemid', $systemid)->first();
$changed = false;
// Looping for all inputs:
$fieldsToCheck = [
'name' => 'product_name',
'prdcategory_id' => 'category',
'prdsubcategory_id' => 'subcategory',
'prdprdcategory_id' => 'prdcategory',
'brand_id' => 'prdbrand',
'description' => 'description',
];
foreach ($fieldsToCheck as $productColumnName => $requestFieldName) {
$requestInput = $request->{$requestFieldName};
if ($request->has($requestFieldName)) {
if ($product_details->$productColumnName != $requestInput) {
$product_details->$productColumnName = $requestInput;
$changed = true;
}
}
// Exception for Sub Category to check for the voucher.
if ($requestFieldName == 'subcategory') {
$this->handleVoucher($requestInput);
}
}
// here I advise you to simply get the dirty version of $product_details
// you can use $product_details->isDirty() // boolean
// or even better use $product_details->wasChanged() // boolean
if ($changed) {
$product_details->save();
$msg = 'Product information updated successfully';
$data = view('layouts.dialog', compact('msg'));
} else {
return back();
// Todo Mo: No need for this line so I commented it out.
//$data = '';
}
} catch (\Exception $e) {
dd($e->getMessage(), 'Oops, error occurred');
}
return $data;
}
private function handleVoucher($product_details, $subcategory)
{
if ($product_details->ptype == 'voucher') {
$voucher = voucher::where('product_id', $product_details->id)->first();
if ($voucher->subcategory_id != $subcategory) {
$voucher->subcategory_id = $subcategory;
$voucher->save();
}
}
}

How to get all routes within a route group?

I need to print a main menu and instead of having a database where the links/ routes are stored I thought it there would be a way to get all routes that are in a named group, but all I find is getting routes by action.
web.php
Route::group(['as' => 'main'], function () {
Route::get('/', function () {
return view('pages.start');
})->name('Home');
Route::get('/foobar', function () {
return view('pages.foobar');
})->name('Home');
Route::get('/business', function () {
return view('pages.business');
})->name('Business');
});
I was looking for something like:
$routes = getRoutesByGroup('main');
I cannot really believe that a function like that doesnt exist in current Laravel but I cant seem to find this. What am I missing?
Maybe this can solve partially in your case
function getRoutesByStarting($start = '')
{
$list = \Route::getRoutes()->getRoutesByName();
if (empty($start)) {
return $list;
}
$routes = [];
foreach ($list as $name => $route) {
if (\Illuminate\Support\Str::startsWith($name, $start)) {
$routes[$name] = $route;
}
}
return $routes;
}
usage
getRoutesByStarting('main')
More general solution
function getRoutesByGroup(array $group = [])
{
$list = \Route::getRoutes()->getRoutes();
if (empty($group)) {
return $list;
}
$routes = [];
foreach ($list as $route) {
$action = $route->getAction();
foreach ($group as $key => $value) {
if (empty($action[$key])) {
continue;
}
$actionValues = Arr::wrap($action[$key]);
$values = Arr::wrap($value);
foreach ($values as $single) {
foreach ($actionValues as $actionValue) {
if (Str::is($single, $actionValue)) {
$routes[] = $route;
} elseif($actionValue == $single) {
$routes[] = $route;
}
}
}
}
}
return $routes;
}
usage
getRoutesByGroup(['middleware' => 'api']);
getRoutesByGroup(['middleware' => ['api']]);
getRoutesByGroup(['as' => 'api']);
getRoutesByGroup(['as' => 'api*']);
getRoutesByGroup(['as' => ['api*', 'main']]);
$allRoutes = Route::getRoutes()->getRoutes(); // fetch all rotues as array
$name = 'main'; // specify your full route name
$grouped_routes = array_filter($allRoutes, function($route) use ($name) {
$action = $route->getAction(); // getting route action
if (isset($action['as'])) {
if (is_array($action['as'])) {
return in_array($name, $action['as']);
} else {
return $action['as'] == $name;
}
}
return false;
});
// output of route objects in the 'main' group
dd($grouped_routes);

when I updating my values a ReflectionException occurs

I want to update actualCost
ProposalExpenses::where('EXPENSE_ID', '=', $request->id)
->update(['ACTUAL_EXPENSES' => $request->actualCost]);
//this my function
public function ProgrameLogExpUploadFiles(Request $request, $proposal_id) {
$officer = officer::where('USER_LOGIN_LOGIN_ID', '=', Auth::user()->LOGIN_ID)->first();
if (isset($request->id)) {
ProposalExpenses::where('EXPENSE_ID', '=', $request->id)
->update(['ACTUAL_EXPENSES' => $request->actualCost]);
if ($request->updated == "true" && $request->balance <= 0) {
$old_files_db = \App\model\programme_proposal\ProgrammeExpenseFileUpload::where([
'PROPOSAL_ID'=>$proposal_id,
'EXPENCE_ID'=>$request->id
])->get();
\App\model\programme_proposal\ProgrammeExpenseFileUpload::where([
'PROPOSAL_ID'=>$proposal_id,
'EXPENCE_ID'=>$request->id
])->delete();
if(isset($old_files_db)){
foreach ($old_files_db as $file) {
try {
\Illuminate\Support\Facades\Storage::delete("programme_expenses/" . $file->STORAGE_FILE_NAME);
} catch (\Exception $e) {
}
}
}
foreach ($request->file as $file) {
$upload_success = $file->store('programme_expenses');
if ($upload_success) {
\App\model\programme_proposal\ProgrammeExpenseFileUpload::create([
'STORAGE_FILE_NAME' => str_replace("programme_expenses/", "", $upload_success),
'REAL_NAME' => $file->getClientOriginalName(),
'UPLOADED_DATE' => \Illuminate\Support\Carbon::now(),
'UPLOADED_BY_STAFF_NIC' => $officer->NIC,
'PROPOSAL_ID' => $proposal_id,
'EXPENCE_ID' => $request->id
]);
}
}
}
if ($request->updated == "false" && $request->balance > 0) {
$old_files_db = \App\model\programme_proposal\ProgrammeExpenseFileUpload::where(['PROPOSAL_ID'=>$proposal_id,'EXPENCE_ID'=>$request->id])->get();
\App\model\programme_proposal\ProgrammeExpenseFileUpload::where(['PROPOSAL_ID'=>$proposal_id,'EXPENCE_ID'=>$request->id])->delete();
if(isset($old_files_db)){
foreach ($old_files_db as $file) {
try {
\Illuminate\Support\Facades\Storage::delete("programme_expenses/" . $file->STORAGE_FILE_NAME);
} catch (\Exception $e) {
}
}
}
}
}
}

This webpage has a redirect loop in Laravel 4

I'm busy with a tutorial and I ended up getting an error that says
This webpage has a redirect loop
I know that the problem is here in my routes.php
Route::group(["before" => "guest"], function(){
$resources = Resource::where("secure", false)->get();
foreach($resources as $resource){
Route::any($resource->pattern, [
"as" => $resource->name,
"uses" => $resource->target
]);
}
});
Route::group(["before" => "auth"], function(){
$resources = Resource::where("secure", true)->get();
foreach($resources as $resource){
Route::any($resource->pattern, [
"as" => $resource->name,
"uses" => $resource->target
]);
}
});
UserController
class UserController extends \BaseController {
public function login()
{
if($this->isPostRequest())
{
$validator = $this->getLoginValidator();
if($validator->passes())
{
$credentials = $this->getLoginCredentials();
if(Auth::attempt($credentials)){
return Redirect::route("user/profile");
}
return Redirect::back()->withErrors([
"password" => ["Credentials invalid."]
]);
}else{
return Redirect::back()
->withInput()
->withErrors($validator);
}
}
return View::make("user/login");
}
protected function isPostRequest()
{
return Input::server("REQUEST_METHOD") == "POST";
}
protected function getLoginValidator()
{
return Validator::make(Input::all(), [
"username" => "required",
"password" => "required"
]);
}
protected function getLoginCredentials()
{
return [
"username" => Input::get("username"),
"password" => Input::get("password")
];
}
public function profile()
{
return View::make("user/profile");
}
public function request()
{
if($this->isPostRequest()){
$response = $this->getPasswordRemindResponse();
if($this->isInvalidUser($response)){
return Redirect::back()
->withInput()
->with("error", Lang::get($response));
}
return Redirect::back()
->with("status", Lang::get($response));
}
return View::make("user/request");
}
protected function getPasswordRemindResponse()
{
return Password::remind(Input::only("email"));
}
protected function isInvalidUser($response)
{
return $response === Password::INVALID_USER;
}
public function reset($token)
{
if($this->isPostRequest()){
$credentials = Input::only(
"email",
"password",
"password_confirmation"
) + compact("token");
$response = $this->resetPassword($credentials);
if($response === Password::PASSWORD_RESET){
return Redirect::route("user/profile");
}
return Redirect::back()
->withInput()
->with("error", Lang::get($response));
}
return View::make("user/reset", compact("token"));
}
protected function resetPassword($credentials)
{
return Password::reset($credentials, function($user, $pass){
$user->password = Hash::make($pass);
$user->save();
});
}
public function logout()
{
Auth::logout();
return Redirect::route("user/login");
}
}
GroupController
class GroupController extends \BaseController {
public function indexAction()
{
return View::make("group/index", [
"groups" => Group::all()
]);
}
public function addAction()
{
$form = new GroupForm();
if($form->isPosted()){
if($form->isValidForAdd()){
Group::create([
"name" => Input::get("name")
]);
return Redirect::route("group/index");
}
return Redirect::route("group/add")->withInput([
"name" => Input::get("name"),
"errors" => $form->getErrors()
]);
}
return View::make("group/add", [
"form" => $form
]);
}
public function editAction()
{
$form = new GroupForm();
$group = Group::findOrFail(Input::get("id"));
$url = URL::full();
if($form->isPosted()){
if($form->isValidForEdit()){
$group->name = Input::get("name");
$group->save();
$group->users()->sync(Input::get("user_id", []));
$group->resources()->sync(Input::get("resource_id", []));
return Redirect::route("group/index");
}
return Redirect::to($url)->withInput([
"name" => Input::get("name"),
"errors" => $form->getErrors(),
"url" => $url
]);
}
return View::make("group/edit", [
"form" => $form,
"group" => $group,
"users" => User::all(),
"resources" => Resource::where("secure", true)->get()
]);
}
public function deleteAction()
{
$form = new GroupForm();
if($form->isValidForDelete()){
$group = Group::findOrFail(Input::get("id"));
$group->delete();
}
return Redirect::route("group/index");
}
}
but I'm not sure how to go about fixing it especially since I was following a tutorial.

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